@digilogiclabs/saas-factory-payments 1.2.6 → 1.2.7
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/{provider-CH-Pf2B0.d.mts → events-CMenJqgf.d.mts} +1 -44
- package/dist/{provider-CH-Pf2B0.d.ts → events-CMenJqgf.d.ts} +1 -44
- package/dist/index.d.mts +4 -2
- package/dist/index.d.ts +4 -2
- package/dist/native.d.mts +68 -3
- package/dist/native.d.ts +68 -3
- package/dist/native.js +1 -1
- package/dist/native.js.map +1 -1
- package/dist/native.mjs +1 -1
- package/dist/native.mjs.map +1 -1
- package/dist/provider-C7F6btFU.d.mts +46 -0
- package/dist/provider-DlAIraLE.d.ts +46 -0
- package/dist/web.d.mts +60 -3
- package/dist/web.d.ts +60 -3
- package/package.json +1 -1
- package/dist/usePayments-Bu8SErKP.d.mts +0 -61
- package/dist/usePayments-Cji_pT1K.d.ts +0 -61
|
@@ -517,47 +517,4 @@ type PaymentEvent = {
|
|
|
517
517
|
error: PaymentError;
|
|
518
518
|
};
|
|
519
519
|
|
|
520
|
-
|
|
521
|
-
name: string;
|
|
522
|
-
initialize(): Promise<void>;
|
|
523
|
-
createCheckoutSession(params: CheckoutParams): Promise<CheckoutSession>;
|
|
524
|
-
retrieveCheckoutSession(sessionId: string): Promise<CheckoutSession>;
|
|
525
|
-
createCustomer(params: CustomerCreateParams): Promise<Customer>;
|
|
526
|
-
retrieveCustomer(customerId: string): Promise<Customer | null>;
|
|
527
|
-
createSubscription(params: SubscriptionCreateParams): Promise<Subscription>;
|
|
528
|
-
cancelSubscription(subscriptionId: string): Promise<void>;
|
|
529
|
-
reactivateSubscription(subscriptionId: string): Promise<void>;
|
|
530
|
-
listSubscriptions(customerId: string, status?: SubscriptionStatus): Promise<Subscription[]>;
|
|
531
|
-
retrieveSubscription(subscriptionId: string): Promise<Subscription | null>;
|
|
532
|
-
updateSubscription(subscriptionId: string, params: SubscriptionUpdateParams): Promise<Subscription>;
|
|
533
|
-
}
|
|
534
|
-
interface PaymentsProviderState {
|
|
535
|
-
customer: Customer | null;
|
|
536
|
-
subscriptions: Subscription[];
|
|
537
|
-
activeSubscription: Subscription | null;
|
|
538
|
-
loading: boolean;
|
|
539
|
-
error: PaymentError | null;
|
|
540
|
-
initialized: boolean;
|
|
541
|
-
config: PaymentsConfig | null;
|
|
542
|
-
isLoading: boolean;
|
|
543
|
-
isError: boolean;
|
|
544
|
-
}
|
|
545
|
-
interface PaymentsProviderActions {
|
|
546
|
-
initialize: (config?: PaymentsConfig) => Promise<void>;
|
|
547
|
-
createCustomer: (params: CustomerCreateParams) => Promise<Customer>;
|
|
548
|
-
retrieveCustomer: (customerId: string) => Promise<Customer | null>;
|
|
549
|
-
createCheckoutSession: (params: CheckoutParams) => Promise<CheckoutSession>;
|
|
550
|
-
retrieveCheckoutSession: (sessionId: string) => Promise<CheckoutSession>;
|
|
551
|
-
createSubscription: (params: SubscriptionCreateParams) => Promise<Subscription>;
|
|
552
|
-
cancelSubscription: (subscriptionId: string) => Promise<void>;
|
|
553
|
-
reactivateSubscription: (subscriptionId: string) => Promise<void>;
|
|
554
|
-
listSubscriptions: (customerId: string, status?: SubscriptionStatus) => Promise<Subscription[]>;
|
|
555
|
-
retrieveSubscription: (subscriptionId: string) => Promise<Subscription | null>;
|
|
556
|
-
updateSubscription: (subscriptionId: string, params: SubscriptionUpdateParams) => Promise<Subscription>;
|
|
557
|
-
refreshCustomer: (customerId: string) => Promise<void>;
|
|
558
|
-
refreshSubscriptions: (customerId: string, status?: SubscriptionStatus) => Promise<void>;
|
|
559
|
-
reset: () => void;
|
|
560
|
-
}
|
|
561
|
-
type PaymentsStore = PaymentsProviderState & PaymentsProviderActions;
|
|
562
|
-
|
|
563
|
-
export { type ActiveSubscriptionStatus as A, type BillingAddress as B, type CheckoutParams as C, type PaymentIntentParams as D, type StripeError as E, type Invoice as F, type PaymentError as G, type PaymentEvent as H, type InactiveSubscriptionStatus as I, type PaymentsProviderState as J, type PaymentsProviderActions as K, type PaymentsStore as L, type PricingPlan as P, SubscriptionStatus as S, type WebhookEvent as W, type PaymentsConfig as a, type PaymentProvider as b, type PaymentProviderType as c, type CheckoutSession as d, type CustomerCreateParams as e, type Customer as f, type SubscriptionCreateParams as g, type Subscription as h, type SubscriptionUpdateParams as i, PaymentErrorType as j, PaymentsError as k, type PaymentMethod as l, type SubscriptionItem as m, type ProblematicSubscriptionStatus as n, type IncompleteSubscriptionStatus as o, ACTIVE_STATUSES as p, INACTIVE_STATUSES as q, PROBLEMATIC_STATUSES as r, INCOMPLETE_STATUSES as s, isActiveSubscription as t, isInactiveSubscription as u, isProblematicSubscription as v, isIncompleteSubscription as w, type CustomerUpdateParams as x, type StripeConfig as y, type CheckoutSessionParams as z };
|
|
520
|
+
export { type ActiveSubscriptionStatus as A, type BillingAddress as B, type CheckoutParams as C, type StripeError as D, type Invoice as E, type PaymentError as F, type PaymentEvent as G, type InactiveSubscriptionStatus as I, type PricingPlan as P, SubscriptionStatus as S, type WebhookEvent as W, type PaymentsConfig as a, type PaymentProviderType as b, type CheckoutSession as c, type CustomerCreateParams as d, type Customer as e, type SubscriptionCreateParams as f, type Subscription as g, type SubscriptionUpdateParams as h, PaymentErrorType as i, PaymentsError as j, type PaymentMethod as k, type SubscriptionItem as l, type ProblematicSubscriptionStatus as m, type IncompleteSubscriptionStatus as n, ACTIVE_STATUSES as o, INACTIVE_STATUSES as p, PROBLEMATIC_STATUSES as q, INCOMPLETE_STATUSES as r, isActiveSubscription as s, isInactiveSubscription as t, isProblematicSubscription as u, isIncompleteSubscription as v, type CustomerUpdateParams as w, type StripeConfig as x, type CheckoutSessionParams as y, type PaymentIntentParams as z };
|
|
@@ -517,47 +517,4 @@ type PaymentEvent = {
|
|
|
517
517
|
error: PaymentError;
|
|
518
518
|
};
|
|
519
519
|
|
|
520
|
-
|
|
521
|
-
name: string;
|
|
522
|
-
initialize(): Promise<void>;
|
|
523
|
-
createCheckoutSession(params: CheckoutParams): Promise<CheckoutSession>;
|
|
524
|
-
retrieveCheckoutSession(sessionId: string): Promise<CheckoutSession>;
|
|
525
|
-
createCustomer(params: CustomerCreateParams): Promise<Customer>;
|
|
526
|
-
retrieveCustomer(customerId: string): Promise<Customer | null>;
|
|
527
|
-
createSubscription(params: SubscriptionCreateParams): Promise<Subscription>;
|
|
528
|
-
cancelSubscription(subscriptionId: string): Promise<void>;
|
|
529
|
-
reactivateSubscription(subscriptionId: string): Promise<void>;
|
|
530
|
-
listSubscriptions(customerId: string, status?: SubscriptionStatus): Promise<Subscription[]>;
|
|
531
|
-
retrieveSubscription(subscriptionId: string): Promise<Subscription | null>;
|
|
532
|
-
updateSubscription(subscriptionId: string, params: SubscriptionUpdateParams): Promise<Subscription>;
|
|
533
|
-
}
|
|
534
|
-
interface PaymentsProviderState {
|
|
535
|
-
customer: Customer | null;
|
|
536
|
-
subscriptions: Subscription[];
|
|
537
|
-
activeSubscription: Subscription | null;
|
|
538
|
-
loading: boolean;
|
|
539
|
-
error: PaymentError | null;
|
|
540
|
-
initialized: boolean;
|
|
541
|
-
config: PaymentsConfig | null;
|
|
542
|
-
isLoading: boolean;
|
|
543
|
-
isError: boolean;
|
|
544
|
-
}
|
|
545
|
-
interface PaymentsProviderActions {
|
|
546
|
-
initialize: (config?: PaymentsConfig) => Promise<void>;
|
|
547
|
-
createCustomer: (params: CustomerCreateParams) => Promise<Customer>;
|
|
548
|
-
retrieveCustomer: (customerId: string) => Promise<Customer | null>;
|
|
549
|
-
createCheckoutSession: (params: CheckoutParams) => Promise<CheckoutSession>;
|
|
550
|
-
retrieveCheckoutSession: (sessionId: string) => Promise<CheckoutSession>;
|
|
551
|
-
createSubscription: (params: SubscriptionCreateParams) => Promise<Subscription>;
|
|
552
|
-
cancelSubscription: (subscriptionId: string) => Promise<void>;
|
|
553
|
-
reactivateSubscription: (subscriptionId: string) => Promise<void>;
|
|
554
|
-
listSubscriptions: (customerId: string, status?: SubscriptionStatus) => Promise<Subscription[]>;
|
|
555
|
-
retrieveSubscription: (subscriptionId: string) => Promise<Subscription | null>;
|
|
556
|
-
updateSubscription: (subscriptionId: string, params: SubscriptionUpdateParams) => Promise<Subscription>;
|
|
557
|
-
refreshCustomer: (customerId: string) => Promise<void>;
|
|
558
|
-
refreshSubscriptions: (customerId: string, status?: SubscriptionStatus) => Promise<void>;
|
|
559
|
-
reset: () => void;
|
|
560
|
-
}
|
|
561
|
-
type PaymentsStore = PaymentsProviderState & PaymentsProviderActions;
|
|
562
|
-
|
|
563
|
-
export { type ActiveSubscriptionStatus as A, type BillingAddress as B, type CheckoutParams as C, type PaymentIntentParams as D, type StripeError as E, type Invoice as F, type PaymentError as G, type PaymentEvent as H, type InactiveSubscriptionStatus as I, type PaymentsProviderState as J, type PaymentsProviderActions as K, type PaymentsStore as L, type PricingPlan as P, SubscriptionStatus as S, type WebhookEvent as W, type PaymentsConfig as a, type PaymentProvider as b, type PaymentProviderType as c, type CheckoutSession as d, type CustomerCreateParams as e, type Customer as f, type SubscriptionCreateParams as g, type Subscription as h, type SubscriptionUpdateParams as i, PaymentErrorType as j, PaymentsError as k, type PaymentMethod as l, type SubscriptionItem as m, type ProblematicSubscriptionStatus as n, type IncompleteSubscriptionStatus as o, ACTIVE_STATUSES as p, INACTIVE_STATUSES as q, PROBLEMATIC_STATUSES as r, INCOMPLETE_STATUSES as s, isActiveSubscription as t, isInactiveSubscription as u, isProblematicSubscription as v, isIncompleteSubscription as w, type CustomerUpdateParams as x, type StripeConfig as y, type CheckoutSessionParams as z };
|
|
520
|
+
export { type ActiveSubscriptionStatus as A, type BillingAddress as B, type CheckoutParams as C, type StripeError as D, type Invoice as E, type PaymentError as F, type PaymentEvent as G, type InactiveSubscriptionStatus as I, type PricingPlan as P, SubscriptionStatus as S, type WebhookEvent as W, type PaymentsConfig as a, type PaymentProviderType as b, type CheckoutSession as c, type CustomerCreateParams as d, type Customer as e, type SubscriptionCreateParams as f, type Subscription as g, type SubscriptionUpdateParams as h, PaymentErrorType as i, PaymentsError as j, type PaymentMethod as k, type SubscriptionItem as l, type ProblematicSubscriptionStatus as m, type IncompleteSubscriptionStatus as n, ACTIVE_STATUSES as o, INACTIVE_STATUSES as p, PROBLEMATIC_STATUSES as q, INCOMPLETE_STATUSES as r, isActiveSubscription as s, isInactiveSubscription as t, isProblematicSubscription as u, isIncompleteSubscription as v, type CustomerUpdateParams as w, type StripeConfig as x, type CheckoutSessionParams as y, type PaymentIntentParams as z };
|
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
import { P as PricingPlan, a as PaymentsConfig, S as SubscriptionStatus, b as
|
|
2
|
-
export {
|
|
1
|
+
import { P as PricingPlan, a as PaymentsConfig, S as SubscriptionStatus, b as PaymentProviderType, C as CheckoutParams, c as CheckoutSession, d as CustomerCreateParams, e as Customer, f as SubscriptionCreateParams, g as Subscription, h as SubscriptionUpdateParams, i as PaymentErrorType, j as PaymentsError, k as PaymentMethod } from './events-CMenJqgf.mjs';
|
|
2
|
+
export { o as ACTIVE_STATUSES, A as ActiveSubscriptionStatus, B as BillingAddress, y as CheckoutSessionParams, w as CustomerUpdateParams, p as INACTIVE_STATUSES, r as INCOMPLETE_STATUSES, I as InactiveSubscriptionStatus, n as IncompleteSubscriptionStatus, E as Invoice, q as PROBLEMATIC_STATUSES, F as PaymentError, G as PaymentEvent, z as PaymentIntentParams, m as ProblematicSubscriptionStatus, x as StripeConfig, D as StripeError, l as SubscriptionItem, W as WebhookEvent, s as isActiveSubscription, t as isInactiveSubscription, v as isIncompleteSubscription, u as isProblematicSubscription } from './events-CMenJqgf.mjs';
|
|
3
|
+
import { P as PaymentProvider } from './provider-C7F6btFU.mjs';
|
|
4
|
+
export { b as PaymentsProviderActions, a as PaymentsProviderState, c as PaymentsStore } from './provider-C7F6btFU.mjs';
|
|
3
5
|
|
|
4
6
|
declare const STRIPE_API_VERSION = "2023-10-16";
|
|
5
7
|
declare const PAYMENT_METHODS: {
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
import { P as PricingPlan, a as PaymentsConfig, S as SubscriptionStatus, b as
|
|
2
|
-
export {
|
|
1
|
+
import { P as PricingPlan, a as PaymentsConfig, S as SubscriptionStatus, b as PaymentProviderType, C as CheckoutParams, c as CheckoutSession, d as CustomerCreateParams, e as Customer, f as SubscriptionCreateParams, g as Subscription, h as SubscriptionUpdateParams, i as PaymentErrorType, j as PaymentsError, k as PaymentMethod } from './events-CMenJqgf.js';
|
|
2
|
+
export { o as ACTIVE_STATUSES, A as ActiveSubscriptionStatus, B as BillingAddress, y as CheckoutSessionParams, w as CustomerUpdateParams, p as INACTIVE_STATUSES, r as INCOMPLETE_STATUSES, I as InactiveSubscriptionStatus, n as IncompleteSubscriptionStatus, E as Invoice, q as PROBLEMATIC_STATUSES, F as PaymentError, G as PaymentEvent, z as PaymentIntentParams, m as ProblematicSubscriptionStatus, x as StripeConfig, D as StripeError, l as SubscriptionItem, W as WebhookEvent, s as isActiveSubscription, t as isInactiveSubscription, v as isIncompleteSubscription, u as isProblematicSubscription } from './events-CMenJqgf.js';
|
|
3
|
+
import { P as PaymentProvider } from './provider-DlAIraLE.js';
|
|
4
|
+
export { b as PaymentsProviderActions, a as PaymentsProviderState, c as PaymentsStore } from './provider-DlAIraLE.js';
|
|
3
5
|
|
|
4
6
|
declare const STRIPE_API_VERSION = "2023-10-16";
|
|
5
7
|
declare const PAYMENT_METHODS: {
|
package/dist/native.d.mts
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
import React from 'react';
|
|
2
2
|
import { ViewStyle, TextStyle } from 'react-native';
|
|
3
|
-
import { P as PricingPlan,
|
|
3
|
+
import { P as PricingPlan, g as Subscription, a as PaymentsConfig, G as PaymentEvent, F as PaymentError, e as Customer, d as CustomerCreateParams, C as CheckoutParams, c as CheckoutSession, h as SubscriptionUpdateParams, S as SubscriptionStatus, j as PaymentsError, k as PaymentMethod } from './events-CMenJqgf.mjs';
|
|
4
4
|
import { PaymentIntent } from '@stripe/stripe-react-native';
|
|
5
|
-
export { P as PaymentsProvider, a as usePayments, u as usePaymentsContext } from './usePayments-Bu8SErKP.mjs';
|
|
6
5
|
|
|
7
6
|
interface CheckoutButtonProps {
|
|
8
7
|
priceId: string;
|
|
@@ -92,6 +91,72 @@ interface StripeProviderProps {
|
|
|
92
91
|
}
|
|
93
92
|
declare const StripeProvider: React.FC<StripeProviderProps>;
|
|
94
93
|
|
|
94
|
+
/**
|
|
95
|
+
* Native-specific PaymentsProvider
|
|
96
|
+
* This provider is designed for React Native applications and uses the native-specific usePayments hook
|
|
97
|
+
* which makes server-side API calls instead of directly using the Node.js Stripe SDK
|
|
98
|
+
*/
|
|
99
|
+
interface PaymentsContextType {
|
|
100
|
+
config: PaymentsConfig | null;
|
|
101
|
+
initialized: boolean;
|
|
102
|
+
loading: boolean;
|
|
103
|
+
error: PaymentError | null;
|
|
104
|
+
customer: Customer | null;
|
|
105
|
+
subscriptions: Subscription[];
|
|
106
|
+
activeSubscription: Subscription | null;
|
|
107
|
+
createCustomer: (params: CustomerCreateParams) => Promise<Customer>;
|
|
108
|
+
createCheckoutSession: (params: CheckoutParams) => Promise<CheckoutSession>;
|
|
109
|
+
cancelSubscription: (subscriptionId: string) => Promise<void>;
|
|
110
|
+
reactivateSubscription: (subscriptionId: string) => Promise<void>;
|
|
111
|
+
updateSubscription: (subscriptionId: string, params: SubscriptionUpdateParams) => Promise<Subscription>;
|
|
112
|
+
refreshCustomer: (customerId: string) => Promise<void>;
|
|
113
|
+
refreshSubscriptions: (customerId: string, status?: SubscriptionStatus) => Promise<void>;
|
|
114
|
+
reset: () => void;
|
|
115
|
+
}
|
|
116
|
+
interface PaymentsProviderProps {
|
|
117
|
+
children: React.ReactNode;
|
|
118
|
+
config?: PaymentsConfig;
|
|
119
|
+
onPaymentSuccess?: (event: PaymentEvent) => void;
|
|
120
|
+
onPaymentError?: (error: PaymentError) => void;
|
|
121
|
+
}
|
|
122
|
+
declare const PaymentsProvider: React.FC<PaymentsProviderProps>;
|
|
123
|
+
declare const usePaymentsContext: () => PaymentsContextType;
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Native-specific usePayments hook
|
|
127
|
+
* This hook is designed for React Native applications and makes server-side API calls
|
|
128
|
+
* instead of directly using the Node.js Stripe SDK
|
|
129
|
+
*/
|
|
130
|
+
interface UsePaymentsStore {
|
|
131
|
+
config: PaymentsConfig | null;
|
|
132
|
+
initialized: boolean;
|
|
133
|
+
loading: boolean;
|
|
134
|
+
error: PaymentsError | null;
|
|
135
|
+
isLoading: boolean;
|
|
136
|
+
isError: boolean;
|
|
137
|
+
customer: Customer | null;
|
|
138
|
+
subscriptions: Subscription[];
|
|
139
|
+
activeSubscription: Subscription | null;
|
|
140
|
+
initialize: (config?: PaymentsConfig) => Promise<void>;
|
|
141
|
+
createCustomer: (params: CustomerCreateParams) => Promise<Customer>;
|
|
142
|
+
retrieveCustomer: (customerId: string) => Promise<Customer | null>;
|
|
143
|
+
createCheckoutSession: (params: CheckoutParams) => Promise<CheckoutSession>;
|
|
144
|
+
retrieveCheckoutSession: (sessionId: string) => Promise<CheckoutSession>;
|
|
145
|
+
createSubscription: (params: {
|
|
146
|
+
priceId: string;
|
|
147
|
+
quantity?: number;
|
|
148
|
+
}) => Promise<Subscription>;
|
|
149
|
+
cancelSubscription: (subscriptionId: string) => Promise<void>;
|
|
150
|
+
reactivateSubscription: (subscriptionId: string) => Promise<void>;
|
|
151
|
+
listSubscriptions: (customerId: string, status?: SubscriptionStatus) => Promise<Subscription[]>;
|
|
152
|
+
retrieveSubscription: (subscriptionId: string) => Promise<Subscription | null>;
|
|
153
|
+
updateSubscription: (subscriptionId: string, params: SubscriptionUpdateParams) => Promise<Subscription>;
|
|
154
|
+
refreshCustomer: (customerId: string) => Promise<void>;
|
|
155
|
+
refreshSubscriptions: (customerId: string, status?: SubscriptionStatus) => Promise<void>;
|
|
156
|
+
reset: () => void;
|
|
157
|
+
}
|
|
158
|
+
declare const usePayments: () => UsePaymentsStore;
|
|
159
|
+
|
|
95
160
|
interface UseSubscriptionOptions {
|
|
96
161
|
customerId?: string;
|
|
97
162
|
subscriptionId?: string;
|
|
@@ -243,4 +308,4 @@ declare const cancelSubscription: (subscriptionId: string) => Promise<{
|
|
|
243
308
|
error?: string;
|
|
244
309
|
}>;
|
|
245
310
|
|
|
246
|
-
export { CheckoutButton, PaymentForm as CheckoutForm, MobilePaymentSheet, type MobilePaymentSheetProps, NativeSubscriptionView, type NativeSubscriptionViewProps, PaymentForm, PricingTable, StripeProvider, TouchIDPayment, type TouchIDPaymentProps, cancelSubscription, createCustomer, createPaymentIntent, createSubscriptionSetup, fetchCustomerSubscriptions, fetchSubscription, formatStripeError, useCheckout, useCustomer, useCheckout as useStripe, useSubscription, validatePaymentsConfig };
|
|
311
|
+
export { CheckoutButton, PaymentForm as CheckoutForm, MobilePaymentSheet, type MobilePaymentSheetProps, NativeSubscriptionView, type NativeSubscriptionViewProps, PaymentForm, PaymentsProvider, PricingTable, StripeProvider, TouchIDPayment, type TouchIDPaymentProps, cancelSubscription, createCustomer, createPaymentIntent, createSubscriptionSetup, fetchCustomerSubscriptions, fetchSubscription, formatStripeError, useCheckout, useCustomer, usePayments, usePaymentsContext, useCheckout as useStripe, useSubscription, validatePaymentsConfig };
|
package/dist/native.d.ts
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
import React from 'react';
|
|
2
2
|
import { ViewStyle, TextStyle } from 'react-native';
|
|
3
|
-
import { P as PricingPlan,
|
|
3
|
+
import { P as PricingPlan, g as Subscription, a as PaymentsConfig, G as PaymentEvent, F as PaymentError, e as Customer, d as CustomerCreateParams, C as CheckoutParams, c as CheckoutSession, h as SubscriptionUpdateParams, S as SubscriptionStatus, j as PaymentsError, k as PaymentMethod } from './events-CMenJqgf.js';
|
|
4
4
|
import { PaymentIntent } from '@stripe/stripe-react-native';
|
|
5
|
-
export { P as PaymentsProvider, a as usePayments, u as usePaymentsContext } from './usePayments-Cji_pT1K.js';
|
|
6
5
|
|
|
7
6
|
interface CheckoutButtonProps {
|
|
8
7
|
priceId: string;
|
|
@@ -92,6 +91,72 @@ interface StripeProviderProps {
|
|
|
92
91
|
}
|
|
93
92
|
declare const StripeProvider: React.FC<StripeProviderProps>;
|
|
94
93
|
|
|
94
|
+
/**
|
|
95
|
+
* Native-specific PaymentsProvider
|
|
96
|
+
* This provider is designed for React Native applications and uses the native-specific usePayments hook
|
|
97
|
+
* which makes server-side API calls instead of directly using the Node.js Stripe SDK
|
|
98
|
+
*/
|
|
99
|
+
interface PaymentsContextType {
|
|
100
|
+
config: PaymentsConfig | null;
|
|
101
|
+
initialized: boolean;
|
|
102
|
+
loading: boolean;
|
|
103
|
+
error: PaymentError | null;
|
|
104
|
+
customer: Customer | null;
|
|
105
|
+
subscriptions: Subscription[];
|
|
106
|
+
activeSubscription: Subscription | null;
|
|
107
|
+
createCustomer: (params: CustomerCreateParams) => Promise<Customer>;
|
|
108
|
+
createCheckoutSession: (params: CheckoutParams) => Promise<CheckoutSession>;
|
|
109
|
+
cancelSubscription: (subscriptionId: string) => Promise<void>;
|
|
110
|
+
reactivateSubscription: (subscriptionId: string) => Promise<void>;
|
|
111
|
+
updateSubscription: (subscriptionId: string, params: SubscriptionUpdateParams) => Promise<Subscription>;
|
|
112
|
+
refreshCustomer: (customerId: string) => Promise<void>;
|
|
113
|
+
refreshSubscriptions: (customerId: string, status?: SubscriptionStatus) => Promise<void>;
|
|
114
|
+
reset: () => void;
|
|
115
|
+
}
|
|
116
|
+
interface PaymentsProviderProps {
|
|
117
|
+
children: React.ReactNode;
|
|
118
|
+
config?: PaymentsConfig;
|
|
119
|
+
onPaymentSuccess?: (event: PaymentEvent) => void;
|
|
120
|
+
onPaymentError?: (error: PaymentError) => void;
|
|
121
|
+
}
|
|
122
|
+
declare const PaymentsProvider: React.FC<PaymentsProviderProps>;
|
|
123
|
+
declare const usePaymentsContext: () => PaymentsContextType;
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Native-specific usePayments hook
|
|
127
|
+
* This hook is designed for React Native applications and makes server-side API calls
|
|
128
|
+
* instead of directly using the Node.js Stripe SDK
|
|
129
|
+
*/
|
|
130
|
+
interface UsePaymentsStore {
|
|
131
|
+
config: PaymentsConfig | null;
|
|
132
|
+
initialized: boolean;
|
|
133
|
+
loading: boolean;
|
|
134
|
+
error: PaymentsError | null;
|
|
135
|
+
isLoading: boolean;
|
|
136
|
+
isError: boolean;
|
|
137
|
+
customer: Customer | null;
|
|
138
|
+
subscriptions: Subscription[];
|
|
139
|
+
activeSubscription: Subscription | null;
|
|
140
|
+
initialize: (config?: PaymentsConfig) => Promise<void>;
|
|
141
|
+
createCustomer: (params: CustomerCreateParams) => Promise<Customer>;
|
|
142
|
+
retrieveCustomer: (customerId: string) => Promise<Customer | null>;
|
|
143
|
+
createCheckoutSession: (params: CheckoutParams) => Promise<CheckoutSession>;
|
|
144
|
+
retrieveCheckoutSession: (sessionId: string) => Promise<CheckoutSession>;
|
|
145
|
+
createSubscription: (params: {
|
|
146
|
+
priceId: string;
|
|
147
|
+
quantity?: number;
|
|
148
|
+
}) => Promise<Subscription>;
|
|
149
|
+
cancelSubscription: (subscriptionId: string) => Promise<void>;
|
|
150
|
+
reactivateSubscription: (subscriptionId: string) => Promise<void>;
|
|
151
|
+
listSubscriptions: (customerId: string, status?: SubscriptionStatus) => Promise<Subscription[]>;
|
|
152
|
+
retrieveSubscription: (subscriptionId: string) => Promise<Subscription | null>;
|
|
153
|
+
updateSubscription: (subscriptionId: string, params: SubscriptionUpdateParams) => Promise<Subscription>;
|
|
154
|
+
refreshCustomer: (customerId: string) => Promise<void>;
|
|
155
|
+
refreshSubscriptions: (customerId: string, status?: SubscriptionStatus) => Promise<void>;
|
|
156
|
+
reset: () => void;
|
|
157
|
+
}
|
|
158
|
+
declare const usePayments: () => UsePaymentsStore;
|
|
159
|
+
|
|
95
160
|
interface UseSubscriptionOptions {
|
|
96
161
|
customerId?: string;
|
|
97
162
|
subscriptionId?: string;
|
|
@@ -243,4 +308,4 @@ declare const cancelSubscription: (subscriptionId: string) => Promise<{
|
|
|
243
308
|
error?: string;
|
|
244
309
|
}>;
|
|
245
310
|
|
|
246
|
-
export { CheckoutButton, PaymentForm as CheckoutForm, MobilePaymentSheet, type MobilePaymentSheetProps, NativeSubscriptionView, type NativeSubscriptionViewProps, PaymentForm, PricingTable, StripeProvider, TouchIDPayment, type TouchIDPaymentProps, cancelSubscription, createCustomer, createPaymentIntent, createSubscriptionSetup, fetchCustomerSubscriptions, fetchSubscription, formatStripeError, useCheckout, useCustomer, useCheckout as useStripe, useSubscription, validatePaymentsConfig };
|
|
311
|
+
export { CheckoutButton, PaymentForm as CheckoutForm, MobilePaymentSheet, type MobilePaymentSheetProps, NativeSubscriptionView, type NativeSubscriptionViewProps, PaymentForm, PaymentsProvider, PricingTable, StripeProvider, TouchIDPayment, type TouchIDPaymentProps, cancelSubscription, createCustomer, createPaymentIntent, createSubscriptionSetup, fetchCustomerSubscriptions, fetchSubscription, formatStripeError, useCheckout, useCustomer, usePayments, usePaymentsContext, useCheckout as useStripe, useSubscription, validatePaymentsConfig };
|
package/dist/native.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";var rt=Object.create;var fe=Object.defineProperty;var ot=Object.getOwnPropertyDescriptor;var nt=Object.getOwnPropertyNames;var it=Object.getPrototypeOf,st=Object.prototype.hasOwnProperty;var at=(o,e)=>{for(var t in e)fe(o,t,{get:e[t],enumerable:!0})},Oe=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of nt(e))!st.call(o,n)&&n!==t&&fe(o,n,{get:()=>e[n],enumerable:!(r=ot(e,n))||r.enumerable});return o};var ct=(o,e,t)=>(t=o!=null?rt(it(o)):{},Oe(e||!o||!o.__esModule?fe(t,"default",{value:o,enumerable:!0}):t,o)),ut=o=>Oe(fe({},"__esModule",{value:!0}),o);var Et={};at(Et,{CheckoutButton:()=>Pe,CheckoutForm:()=>Ee,MobilePaymentSheet:()=>Ye,NativeSubscriptionView:()=>je,PaymentForm:()=>Ee,PaymentsProvider:()=>Ae,PricingTable:()=>$e,StripeProvider:()=>Xe,TouchIDPayment:()=>He,cancelSubscription:()=>Ct,createCustomer:()=>bt,createPaymentIntent:()=>yt,createSubscriptionSetup:()=>ft,fetchCustomerSubscriptions:()=>St,fetchSubscription:()=>gt,formatStripeError:()=>Pt,useCheckout:()=>Te,useCustomer:()=>tt,usePayments:()=>Ze,usePaymentsContext:()=>H,useStripe:()=>Te,useSubscription:()=>Qe,validatePaymentsConfig:()=>ht});module.exports=ut(Et);var Ve=require("react"),Q=require("react-native"),Be=require("@stripe/stripe-react-native");var Z=require("react");var Ne=require("zustand"),De=require("zustand/middleware/immer");var u=class o extends Error{type;code;details;constructor(e,t,r,n){super(t),this.name="PaymentsError",this.type=e,this.code=r,this.details=n,Object.setPrototypeOf(this,o.prototype)}};var ne=class{config;constructor(e){this.config=e}handleError(e,t="UNKNOWN_ERROR"){if(e instanceof u)return e;let r="An unknown error occurred",n,i;return typeof e=="object"&&e!==null&&("message"in e&&typeof e.message=="string"&&(r=e.message),"code"in e&&typeof e.code=="string"&&(n=e.code),i={...e}),new u(t,r,n,i)}};var ve=ct(require("stripe")),ye=class extends ne{name="stripe";stripeClient;constructor(e){if(super(e),!e.stripeConfig?.publishableKey)throw new u("CONFIGURATION_ERROR","Stripe publishable key is missing in config.");if(!process.env.STRIPE_SECRET_KEY)throw new u("CONFIGURATION_ERROR","STRIPE_SECRET_KEY environment variable is not set.");this.stripeClient=new ve.default(process.env.STRIPE_SECRET_KEY,{apiVersion:"2024-06-20"})}async initialize(){console.log("StripePaymentProvider initialized (server-side)")}async createCheckoutSession(e){try{let t=await this.stripeClient.checkout.sessions.create({payment_method_types:["card"],line_items:[{price:e.priceId,quantity:1}],mode:e.mode||"payment",success_url:e.successUrl||`${process.env.NEXT_PUBLIC_BASE_URL}/success?session_id={CHECKOUT_SESSION_ID}`,cancel_url:e.cancelUrl||`${process.env.NEXT_PUBLIC_BASE_URL}/cancel`,customer_email:e.customerEmail,allow_promotion_codes:e.allowPromotionCodes,metadata:e.metadata});if(!t.url)throw new u("UNKNOWN_ERROR","Stripe checkout session URL is missing.");return{id:t.id,url:t.url,status:t.status,amountTotal:t.amount_total||void 0,currency:t.currency||void 0,customerEmail:t.customer_details?.email||void 0,subscriptionId:t.subscription?.toString()||void 0}}catch(t){throw this.handleError(t,"NETWORK_ERROR")}}async createCustomer(e){try{let t=await this.stripeClient.customers.create({email:e.email,name:e.name,metadata:e.metadata});return{id:t.id,email:t.email||e.email,name:t.name||e.name,phone:null,stripeCustomerId:t.id,subscriptions:[],paymentMethods:[],defaultPaymentMethodId:null,metadata:t.metadata,created:new Date(t.created*1e3),updated:new Date(t.created*1e3)}}catch(t){throw this.handleError(t,"NETWORK_ERROR")}}async retrieveCustomer(e){try{let t=await this.stripeClient.customers.retrieve(e);return t.deleted?null:{id:t.id,email:t.email||"",name:t.name||void 0,phone:t.phone||void 0,stripeCustomerId:t.id,subscriptions:[],paymentMethods:[],defaultPaymentMethodId:t.invoice_settings?.default_payment_method?.toString()||void 0,metadata:t.metadata,created:new Date(t.created*1e3),updated:new Date(t.created*1e3)}}catch(t){throw this.handleError(t,"NETWORK_ERROR")}}async createSubscription(e){try{let t=await this.stripeClient.subscriptions.create({customer:e.customerId,items:(e.items||(e.priceId?[{priceId:e.priceId,quantity:1}]:[])).map(r=>({price:r.priceId,quantity:r.quantity||1})),trial_period_days:e.trialPeriodDays,metadata:e.metadata,expand:["latest_invoice.payment_intent"]});return this.mapStripeSubscriptionToSubscription(t)}catch(t){throw this.handleError(t,"NETWORK_ERROR")}}async cancelSubscription(e){try{await this.stripeClient.subscriptions.cancel(e)}catch(t){throw this.handleError(t,"NETWORK_ERROR")}}async reactivateSubscription(e){try{let t=await this.stripeClient.subscriptions.retrieve(e);if(t.status==="canceled"&&t.cancel_at_period_end)await this.stripeClient.subscriptions.update(e,{cancel_at_period_end:!1});else throw new u("VALIDATION_ERROR","Subscription cannot be reactivated.")}catch(t){throw this.handleError(t,"NETWORK_ERROR")}}async retrieveCheckoutSession(e){try{let t=await this.stripeClient.checkout.sessions.retrieve(e);if(!t.url)throw new u("UNKNOWN_ERROR","Stripe checkout session URL is missing.");return{id:t.id,url:t.url,status:t.status,amountTotal:t.amount_total||void 0,currency:t.currency||void 0,customerEmail:t.customer_details?.email||void 0,subscriptionId:t.subscription?.toString()||void 0}}catch(t){throw this.handleError(t,"NETWORK_ERROR")}}async listSubscriptions(e,t){try{return(await this.stripeClient.subscriptions.list({customer:e,status:t==="all"?void 0:t})).data.map(this.mapStripeSubscriptionToSubscription)}catch(r){throw this.handleError(r,"NETWORK_ERROR")}}async retrieveSubscription(e){try{let t=await this.stripeClient.subscriptions.retrieve(e);return this.mapStripeSubscriptionToSubscription(t)}catch(t){throw this.handleError(t,"NETWORK_ERROR")}}async updateSubscription(e,t){try{let r=await this.stripeClient.subscriptions.retrieve(e),n=t.items?t.items.map(d=>({id:r.items.data.find(c=>c.price?.id===d.priceId)?.id,price:d.priceId,quantity:d.quantity||1})):void 0,i=await this.stripeClient.subscriptions.update(e,{items:n,metadata:t.metadata});return this.mapStripeSubscriptionToSubscription(i)}catch(r){throw this.handleError(r,"NETWORK_ERROR")}}mapStripeSubscriptionToSubscription(e){return{id:e.id,customerId:e.customer.toString(),status:e.status,items:e.items.data.map(t=>({id:t.id,priceId:t.price?.id||"",quantity:t.quantity||1})),currentPeriodStart:new Date(e.current_period_start*1e3),currentPeriodEnd:new Date(e.current_period_end*1e3),cancelAtPeriodEnd:e.cancel_at_period_end,trialStart:e.trial_start?new Date(e.trial_start*1e3):void 0,trialEnd:e.trial_end?new Date(e.trial_end*1e3):void 0,metadata:e.metadata,created:new Date(e.created*1e3),updated:new Date(e.created*1e3)}}};var he=class extends ne{name="MockPaymentProvider";customers=[];subscriptions=[];nextCustomerId=1;nextSubscriptionId=1;constructor(e){super({...e,provider:"mock"}),console.log("MockPaymentProvider initialized")}async initialize(){console.log("MockPaymentProvider initialized")}async createCheckoutSession(e){return console.log("Mock: createCheckoutSession",e),{id:"mock_cs_123",clientSecret:"mock_client_secret",url:"https://mock-checkout.example.com/success",status:"open"}}async retrieveCheckoutSession(e){if(console.log("Mock: retrieveCheckoutSession",e),e==="mock_cs_123")return{id:"mock_cs_123",clientSecret:"mock_client_secret",url:"https://mock-checkout.example.com/success",status:"complete"};throw new u("CUSTOMER_NOT_FOUND",`Mock checkout session ${e} not found`)}async createCustomer(e){console.log("Mock: createCustomer",e);let t={id:`mock_cus_${this.nextCustomerId++}`,email:e.email,name:e.name||null,phone:e.phone||null,stripeCustomerId:null,subscriptions:[],defaultPaymentMethodId:null,paymentMethods:[],metadata:e.metadata||{},created:new Date,updated:new Date};return this.customers.push(t),t}async retrieveCustomer(e){console.log("Mock: retrieveCustomer",e);let t=this.customers.find(r=>r.id===e);if(!t)throw new u("CUSTOMER_NOT_FOUND",`Mock customer ${e} not found`);return t}async updateCustomer(e,t){console.log("Mock: updateCustomer",e,t);let r=this.customers.find(n=>n.id===e);if(!r)throw new u("CUSTOMER_NOT_FOUND",`Mock customer ${e} not found`);return t.email&&(r.email=t.email),t.name&&(r.name=t.name),t.phone&&(r.phone=t.phone),t.metadata&&(r.metadata={...r.metadata,...t.metadata}),r.updated=new Date,r}async deleteCustomer(e){console.log("Mock: deleteCustomer",e);let t=this.customers.length;if(this.customers=this.customers.filter(r=>r.id!==e),this.customers.length===t)throw new u("CUSTOMER_NOT_FOUND",`Mock customer ${e} not found`)}async listPaymentMethods(e){console.log("Mock: listPaymentMethods",e);let t=this.customers.find(r=>r.id===e);if(!t)throw new u("CUSTOMER_NOT_FOUND",`Mock customer ${e} not found`);return t.paymentMethods||[]}async attachPaymentMethod(e,t){console.log("Mock: attachPaymentMethod",e,t);let r=this.customers.find(i=>i.id===e);if(!r)throw new u("CUSTOMER_NOT_FOUND",`Mock customer ${e} not found`);let n={id:t,type:"card",card:{brand:"visa",last4:"4242",expMonth:12,expYear:2025,country:"US"},isDefault:!1,created:new Date};return r.paymentMethods.push(n),n}async detachPaymentMethod(e,t){console.log("Mock: detachPaymentMethod",e,t);let r=this.customers.find(i=>i.id===e);if(!r)throw new u("CUSTOMER_NOT_FOUND",`Mock customer ${e} not found`);let n=r.paymentMethods.length;if(r.paymentMethods=r.paymentMethods.filter(i=>i.id!==t),r.paymentMethods.length===n)throw new u("CUSTOMER_NOT_FOUND",`Mock payment method ${t} not found for customer ${e}`)}async createSubscription(e){console.log("Mock: createSubscription",e);let t=this.customers.find(n=>n.id===e.customerId);if(!t)throw new u("CUSTOMER_NOT_FOUND",`Mock customer ${e.customerId} not found`);let r={id:`mock_sub_${this.nextSubscriptionId++}`,customerId:e.customerId,status:"active",items:(e.items||(e.priceId?[{priceId:e.priceId,quantity:1}]:[])).map(n=>({id:`mock_sub_item_${Math.random().toString(36).substring(7)}`,priceId:n.priceId,quantity:n.quantity||1})),currentPeriodStart:new Date,currentPeriodEnd:new Date(Date.now()+720*60*60*1e3),cancelAtPeriodEnd:!1,created:new Date,updated:new Date};return this.subscriptions.push(r),t.subscriptions.push(r),r}async retrieveSubscription(e){console.log("Mock: retrieveSubscription",e);let t=this.subscriptions.find(r=>r.id===e);if(!t)throw new u("SUBSCRIPTION_NOT_FOUND",`Mock subscription ${e} not found`);return t}async updateSubscription(e,t){console.log("Mock: updateSubscription",e,t);let r=this.subscriptions.find(n=>n.id===e);if(!r)throw new u("SUBSCRIPTION_NOT_FOUND",`Mock subscription ${e} not found`);return t.cancelAtPeriodEnd!==void 0&&(r.cancelAtPeriodEnd=t.cancelAtPeriodEnd,r.status=t.cancelAtPeriodEnd?"canceled":"active"),t.items&&(r.items=t.items.map(n=>({id:`mock_sub_item_${Math.random().toString(36).substring(7)}`,priceId:n.priceId,quantity:n.quantity||1}))),r.updated=new Date,r}async cancelSubscription(e){console.log("Mock: cancelSubscription",e);let t=this.subscriptions.find(r=>r.id===e);if(!t)throw new u("SUBSCRIPTION_NOT_FOUND",`Mock subscription ${e} not found`);t.status="canceled",t.cancelAtPeriodEnd=!0,t.updated=new Date}async reactivateSubscription(e){console.log("Mock: reactivateSubscription",e);let t=this.subscriptions.find(r=>r.id===e);if(!t)throw new u("SUBSCRIPTION_NOT_FOUND",`Mock subscription ${e} not found`);t.status="active",t.cancelAtPeriodEnd=!1,t.updated=new Date}async listSubscriptions(e,t){console.log("Mock: listSubscriptions",e,t);let r=this.customers.find(i=>i.id===e);if(!r)throw new u("CUSTOMER_NOT_FOUND",`Mock customer ${e} not found`);let n=r.subscriptions;return t&&t!=="all"&&(n=n.filter(i=>i.status===t)),n}};var z=class{static create(e){switch(e.provider){case"stripe":return new ye(e);case"paypal":throw new u("PROVIDER_NOT_CONFIGURED","PayPal provider is not yet available in this build");case"applepay":throw new u("PROVIDER_NOT_CONFIGURED","Apple Pay provider is not yet available in this build");case"mock":return new he(e);default:throw new u("CONFIGURATION_ERROR",`Unsupported payment provider: ${e.provider}`)}}static autodetect(){if(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY&&process.env.STRIPE_SECRET_KEY)return{provider:"stripe",publishableKey:process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY,environment:process.env.NODE_ENV==="production"?"production":"development",stripeConfig:{publishableKey:process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY}};if(process.env.NEXT_PUBLIC_PAYPAL_CLIENT_ID&&process.env.PAYPAL_CLIENT_SECRET)return{provider:"paypal",publishableKey:process.env.NEXT_PUBLIC_PAYPAL_CLIENT_ID,environment:process.env.NODE_ENV==="production"?"production":"development",paypalConfig:{clientId:process.env.NEXT_PUBLIC_PAYPAL_CLIENT_ID,clientSecret:process.env.PAYPAL_CLIENT_SECRET,environment:process.env.NODE_ENV==="production"?"production":"sandbox",currency:process.env.PAYPAL_CURRENCY||"USD"}};if(process.env.NEXT_PUBLIC_APPLE_PAY_MERCHANT_ID&&typeof window<"u"&&window.ApplePaySession)return{provider:"applepay",environment:process.env.NODE_ENV==="production"?"production":"development",applePayConfig:{merchantId:process.env.NEXT_PUBLIC_APPLE_PAY_MERCHANT_ID,merchantName:process.env.NEXT_PUBLIC_APPLE_PAY_MERCHANT_NAME||"Your Store",countryCode:process.env.NEXT_PUBLIC_APPLE_PAY_COUNTRY_CODE||"US",currencyCode:process.env.NEXT_PUBLIC_APPLE_PAY_CURRENCY_CODE||"USD",environment:process.env.NODE_ENV==="production"?"production":"sandbox"}};if(process.env.NODE_ENV!=="production"||process.env.VERCEL_ENV==="preview")return console.warn("No payment provider detected, defaulting to MockPaymentProvider for development/preview environment."),{provider:"mock",environment:"development"};throw new u("CONFIGURATION_ERROR","Could not auto-detect payment provider. Please provide explicit configuration.")}static getAvailableProviders(){let e=[];return process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY&&e.push("stripe"),process.env.NEXT_PUBLIC_PAYPAL_CLIENT_ID&&e.push("paypal"),typeof window<"u"&&window.ApplePaySession?.canMakePayments()&&e.push("applepay"),process.env.NODE_ENV!=="production"&&e.push("mock"),e}static createMultiple(e){return e.map(t=>this.create(t))}};var _e={customer:null,subscriptions:[],activeSubscription:null,loading:!1,error:null,initialized:!1,config:null,isLoading:!1,isError:!1},ke=(0,Ne.create)()((0,De.immer)((o,e)=>({..._e,get isLoading(){return e().loading},get isError(){return!!e().error},initialize:async t=>{o(r=>{r.loading=!0,r.error=null});try{let r;t?r=t:r=z.autodetect(),await z.create(r).initialize(),o(i=>{i.initialized=!0,i.loading=!1,i.config=r})}catch(r){throw o(n=>{let i=r instanceof Error?r.message:"Failed to initialize payments provider.";n.error=new u("CONFIGURATION_ERROR",i),n.loading=!1}),r}},createCustomer:async t=>{o(r=>{r.loading=!0,r.error=null});try{if(!e().config)throw new u("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await z.create(e().config).createCustomer(t);return o(i=>{i.customer=n,i.loading=!1}),n}catch(r){throw o(n=>{let i=r instanceof Error?r.message:"Failed to create customer.";n.error=new u("NETWORK_ERROR",i),n.loading=!1}),r}},retrieveCustomer:async t=>{o(r=>{r.loading=!0,r.error=null});try{if(!e().config)throw new u("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await z.create(e().config).retrieveCustomer(t);return o(i=>{i.customer=n,i.loading=!1}),n}catch(r){throw o(n=>{let i=r instanceof Error?r.message:"Failed to retrieve customer.";n.error=new u("NETWORK_ERROR",i),n.loading=!1}),r}},createCheckoutSession:async t=>{o(r=>{r.loading=!0,r.error=null});try{if(!e().config)throw new u("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await z.create(e().config).createCheckoutSession(t);return o(i=>{i.loading=!1}),n}catch(r){throw o(n=>{let i=r instanceof Error?r.message:"Failed to create checkout session.";n.error=new u("NETWORK_ERROR",i),n.loading=!1}),r}},retrieveCheckoutSession:async t=>{o(r=>{r.loading=!0,r.error=null});try{if(!e().config)throw new u("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await z.create(e().config).retrieveCheckoutSession(t);return o(i=>{i.loading=!1}),n}catch(r){throw o(n=>{let i=r instanceof Error?r.message:"Failed to retrieve checkout session.";n.error=new u("NETWORK_ERROR",i),n.loading=!1}),r}},createSubscription:async t=>{o(r=>{r.loading=!0,r.error=null});try{if(!e().config)throw new u("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await z.create(e().config).createSubscription(t);return await e().refreshSubscriptions(e().customer?.id||""),o(i=>{i.loading=!1}),n}catch(r){throw o(n=>{let i=r instanceof Error?r.message:"Failed to create subscription.";n.error=new u("NETWORK_ERROR",i),n.loading=!1}),r}},cancelSubscription:async t=>{o(r=>{r.loading=!0,r.error=null});try{if(!e().config)throw new u("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");await z.create(e().config).cancelSubscription(t),await e().refreshSubscriptions(e().customer?.id||""),o(n=>{n.loading=!1})}catch(r){throw o(n=>{let i=r instanceof Error?r.message:"Failed to cancel subscription.";n.error=new u("NETWORK_ERROR",i),n.loading=!1}),r}},reactivateSubscription:async t=>{o(r=>{r.loading=!0,r.error=null});try{if(!e().config)throw new u("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");await z.create(e().config).reactivateSubscription(t),await e().refreshSubscriptions(e().customer?.id||""),o(n=>{n.loading=!1})}catch(r){throw o(n=>{let i=r instanceof Error?r.message:"Failed to reactivate subscription.";n.error=new u("NETWORK_ERROR",i),n.loading=!1}),r}},updateSubscription:async(t,r)=>{o(n=>{n.loading=!0,n.error=null});try{if(!e().config)throw new u("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let i=await z.create(e().config).updateSubscription(t,r);return await e().refreshSubscriptions(e().customer?.id||""),o(d=>{d.loading=!1}),i}catch(n){throw o(i=>{let d=n instanceof Error?n.message:"Failed to update subscription.";i.error=new u("NETWORK_ERROR",d),i.loading=!1}),n}},listSubscriptions:async(t,r)=>{o(n=>{n.loading=!0,n.error=null});try{if(!e().config)throw new u("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let i=await z.create(e().config).listSubscriptions(t,r);return o(d=>{d.subscriptions=i,d.loading=!1}),i}catch(n){throw o(i=>{let d=n instanceof Error?n.message:"Failed to list subscriptions.";i.error=new u("NETWORK_ERROR",d),i.loading=!1}),n}},retrieveSubscription:async t=>{o(r=>{r.loading=!0,r.error=null});try{if(!e().config)throw new u("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await z.create(e().config).retrieveSubscription(t);return o(i=>{i.loading=!1}),n}catch(r){throw o(n=>{let i=r instanceof Error?r.message:"Failed to retrieve subscription.";n.error=new u("NETWORK_ERROR",i),n.loading=!1}),r}},refreshCustomer:async t=>{o(r=>{r.loading=!0,r.error=null});try{if(!e().config)throw new u("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await z.create(e().config).retrieveCustomer(t);o(i=>{i.customer=n,i.loading=!1})}catch(r){o(n=>{let i=r instanceof Error?r.message:"Failed to refresh customer.";n.error=new u("NETWORK_ERROR",i),n.loading=!1})}},refreshSubscriptions:async(t,r)=>{o(n=>{n.loading=!0,n.error=null});try{if(!e().config)throw new u("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let i=await z.create(e().config).listSubscriptions(t,r),d=i.find(c=>c.status==="active"||c.status==="trialing")||null;o(c=>{c.subscriptions=i,c.activeSubscription=d,c.loading=!1})}catch(n){o(i=>{let d=n instanceof Error?n.message:"Failed to refresh subscriptions.";i.error=new u("NETWORK_ERROR",d),i.loading=!1})}},reset:()=>{o(t=>{Object.assign(t,_e)})}})));var Fe=require("react/jsx-runtime"),xe=(0,Z.createContext)(void 0),Ae=({children:o,config:e,onPaymentSuccess:t,onPaymentError:r})=>{let n=ke(),{initialize:i,initialized:d,loading:c,error:m,customer:b,subscriptions:P,activeSubscription:g}=n,x=(0,Z.useRef)(t),D=(0,Z.useRef)(r);(0,Z.useEffect)(()=>{x.current=t},[t]),(0,Z.useEffect)(()=>{D.current=r},[r]),(0,Z.useEffect)(()=>{!d&&!c&&!m&&i(e).catch(S=>{console.error("PaymentsProvider initialization failed:",S),D.current&&D.current(S)})},[d,c,m,e,i]);let s={config:n.config,initialized:d,loading:c,error:m,customer:b,subscriptions:P,activeSubscription:g,createCustomer:n.createCustomer,createCheckoutSession:n.createCheckoutSession,cancelSubscription:n.cancelSubscription,reactivateSubscription:n.reactivateSubscription,updateSubscription:n.updateSubscription,refreshCustomer:n.refreshCustomer,refreshSubscriptions:n.refreshSubscriptions,reset:n.reset};return(0,Fe.jsx)(xe.Provider,{value:s,children:o})},H=()=>{let o=(0,Z.useContext)(xe);if(o===void 0)throw new Error("usePaymentsContext must be used within a PaymentsProvider");return o};var Ue={USD:"$",EUR:"\u20AC",GBP:"\xA3",JPY:"\xA5",CAD:"C$",AUD:"A$",CHF:"CHF",CNY:"\xA5",SEK:"kr",NZD:"NZ$"},Me="USD";var h={PROVIDER_NOT_CONFIGURED:"Payments provider is not properly configured",STRIPE_NOT_LOADED:"Stripe has not been loaded yet",INVALID_PRICE_ID:"Invalid price ID provided",INVALID_CUSTOMER_ID:"Invalid customer ID provided",CHECKOUT_FAILED:"Checkout session creation failed",PAYMENT_FAILED:"Payment processing failed",SUBSCRIPTION_NOT_FOUND:"Subscription not found",CUSTOMER_NOT_FOUND:"Customer not found"};var te=o=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(o);var G=(o,e)=>{let t={customer:"cus_",subscription:"sub_",price:"price_",product:"prod_",payment_intent:"pi_"};return o.startsWith(t[e])};var le=require("react/jsx-runtime"),Pe=({priceId:o,customerId:e,customerEmail:t,children:r,style:n,textStyle:i,disabled:d=!1,metadata:c,trialPeriodDays:m,onSuccess:b,onError:P,onLoading:g})=>{let{initPaymentSheet:x,presentPaymentSheet:D}=(0,Be.useStripe)(),{initialized:s}=H(),[S,M]=(0,Ve.useState)(!1),k=R=>{P?.(R),Q.Alert.alert("Payment Error",R),console.error("Checkout error:",R)},q=async()=>{if(!s){k(h.PROVIDER_NOT_CONFIGURED);return}if(!G(o,"price")){k(h.INVALID_PRICE_ID);return}if(e&&!G(e,"customer")){k(h.INVALID_CUSTOMER_ID);return}M(!0),g?.(!0);try{let R=await fetch("/api/payments/create-subscription-setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({priceId:o,customerId:e,customerEmail:t,metadata:c,trialPeriodDays:m})});if(!R.ok){let l=await R.json().catch(()=>({error:"Network error"}));throw new Error(l.error||h.CHECKOUT_FAILED)}let{setupIntentClientSecret:a,customerId:p,customerEphemeralKeySecret:v}=await R.json();if(!a)throw new Error("No setup intent client secret returned from server");let{error:T}=await x({setupIntentClientSecret:a,customerId:p,customerEphemeralKeySecret:v,merchantDisplayName:"Your App Name",allowsDelayedPaymentMethods:!0});if(T)throw new Error(T.message||"Failed to initialize payment sheet");let{error:f}=await D();if(f){if(f.code!=="Canceled")throw new Error(f.message||h.PAYMENT_FAILED);return}b?.()}catch(R){let a=R instanceof Error?R.message:h.CHECKOUT_FAILED;k(a)}finally{M(!1),g?.(!1)}},O=S||d||!s;return(0,le.jsxs)(Q.TouchableOpacity,{style:[ue.button,n,O&&ue.disabled],onPress:q,disabled:O,activeOpacity:.8,children:[S?(0,le.jsx)(Q.ActivityIndicator,{color:"#ffffff",size:"small",style:ue.loader}):null,(0,le.jsx)(Q.Text,{style:[ue.buttonText,i,S&&ue.loadingText],children:S?"Processing...":r})]})},ue=Q.StyleSheet.create({button:{backgroundColor:"#007AFF",paddingHorizontal:16,paddingVertical:12,borderRadius:8,flexDirection:"row",alignItems:"center",justifyContent:"center",minHeight:48},buttonText:{color:"#ffffff",fontSize:16,fontWeight:"600",textAlign:"center"},disabled:{opacity:.5},loader:{marginRight:8},loadingText:{marginLeft:8}});var F=require("react-native");var Ce=(o,e=Me,t={})=>{let{showSymbol:r=!0,showCents:n=!0,locale:i="en-US"}=t,d=e.toUpperCase(),c=["JPY","KRW","VND","CLP"].includes(d),m=c?o:o/100;if(r)try{return new Intl.NumberFormat(i,{style:"currency",currency:d,minimumFractionDigits:n&&!c?2:0,maximumFractionDigits:n&&!c?2:0}).format(m)}catch{let b=Ue[d]||d,P=n&&!c?m.toFixed(2):Math.round(m).toString();return`${b}${P}`}return n&&!c?m.toFixed(2):Math.round(m).toString()},Le=o=>{let e=Ce(o.price,o.currency),t=o.intervalCount&&o.intervalCount>1?`${o.intervalCount} ${o.interval}s`:o.interval;return`${e}/${t}`};var me=(o,e={})=>{let{format:t="medium",locale:r="en-US",timeZone:n}=e,i=typeof o=="string"||typeof o=="number"?new Date(o):o,d={timeZone:n};switch(t){case"short":d.dateStyle="short";break;case"medium":d.dateStyle="medium";break;case"long":d.dateStyle="long";break;case"full":d.dateStyle="full";break}try{return new Intl.DateTimeFormat(r,d).format(i)}catch{return i.toLocaleDateString()}};var ze=o=>o===0?"No trial":o===1?"1 day trial":o<7?`${o} days trial`:o===7?"1 week trial":o<30?`${Math.floor(o/7)} weeks trial`:o===30?"1 month trial":`${Math.floor(o/30)} months trial`;var V=require("react/jsx-runtime"),{width:Ke}=F.Dimensions.get("window"),$e=({plans:o,customerId:e,customerEmail:t,onCheckoutSuccess:r,onCheckoutError:n,showFeatures:i=!0,showTrialInfo:d=!0,layout:c="carousel",containerStyle:m})=>{if(!o||o.length===0)return(0,V.jsx)(F.View,{style:A.emptyContainer,children:(0,V.jsx)(F.Text,{style:A.emptyText,children:"No pricing plans available"})});let b=P=>(0,V.jsx)(lt,{plan:P,customerId:e,customerEmail:t,onCheckoutSuccess:()=>r?.(P),onCheckoutError:g=>n?.(P,g),showFeatures:i,showTrialInfo:d,style:c==="carousel"?A.carouselCard:A.listCard},P.id);return c==="carousel"?(0,V.jsx)(F.View,{style:[A.container,m],children:(0,V.jsx)(F.ScrollView,{horizontal:!0,showsHorizontalScrollIndicator:!1,contentContainerStyle:A.carouselContainer,snapToInterval:Ke*.8+16,decelerationRate:"fast",children:o.map(b)})}):(0,V.jsx)(F.ScrollView,{style:[A.container,m],children:(0,V.jsx)(F.View,{style:A.listContainer,children:o.map(b)})})},lt=({plan:o,customerId:e,customerEmail:t,onCheckoutSuccess:r,onCheckoutError:n,showFeatures:i=!0,showTrialInfo:d=!0,style:c})=>{let m=o.popular;return(0,V.jsxs)(F.View,{style:[A.card,m&&A.popularCard,c],children:[m&&(0,V.jsx)(F.View,{style:A.popularBadge,children:(0,V.jsx)(F.Text,{style:A.popularBadgeText,children:"Most Popular"})}),(0,V.jsxs)(F.View,{style:A.cardHeader,children:[(0,V.jsx)(F.Text,{style:A.planName,children:o.name}),o.description&&(0,V.jsx)(F.Text,{style:A.planDescription,children:o.description}),(0,V.jsx)(F.Text,{style:A.planPrice,children:Le(o)}),d&&o.trialPeriodDays&&o.trialPeriodDays>0&&(0,V.jsx)(F.Text,{style:A.trialInfo,children:ze(o.trialPeriodDays)})]}),i&&o.features&&o.features.length>0&&(0,V.jsx)(F.View,{style:A.featuresContainer,children:o.features.map((b,P)=>(0,V.jsxs)(F.View,{style:A.featureItem,children:[(0,V.jsx)(F.Text,{style:A.featureCheckmark,children:"\u2713"}),(0,V.jsx)(F.Text,{style:A.featureText,children:b})]},P))}),(0,V.jsx)(F.View,{style:A.buttonContainer,children:(0,V.jsx)(Pe,{priceId:o.stripePriceId,customerId:e,customerEmail:t,trialPeriodDays:o.trialPeriodDays,metadata:o.metadata,onSuccess:r,onError:n,style:[A.ctaButton,m?A.popularButton:A.regularButton],textStyle:[A.ctaButtonText,m?A.popularButtonText:A.regularButtonText],children:"Get Started"})})]})},A=F.StyleSheet.create({container:{flex:1},emptyContainer:{flex:1,justifyContent:"center",alignItems:"center",padding:20},emptyText:{fontSize:16,color:"#666",textAlign:"center"},carouselContainer:{paddingHorizontal:16},listContainer:{padding:16},carouselCard:{width:Ke*.8,marginRight:16},listCard:{marginBottom:16},card:{backgroundColor:"#ffffff",borderRadius:12,padding:20,shadowColor:"#000",shadowOffset:{width:0,height:2},shadowOpacity:.1,shadowRadius:8,elevation:4,borderWidth:1,borderColor:"#e0e0e0"},popularCard:{borderColor:"#007AFF",borderWidth:2},popularBadge:{position:"absolute",top:-1,left:-1,right:-1,backgroundColor:"#007AFF",paddingVertical:8,borderTopLeftRadius:12,borderTopRightRadius:12,alignItems:"center"},popularBadgeText:{color:"#ffffff",fontSize:12,fontWeight:"600"},cardHeader:{alignItems:"center",marginBottom:20,marginTop:20},planName:{fontSize:20,fontWeight:"700",color:"#333",marginBottom:8,textAlign:"center"},planDescription:{fontSize:14,color:"#666",textAlign:"center",marginBottom:16,lineHeight:20},planPrice:{fontSize:28,fontWeight:"800",color:"#333",marginBottom:8,textAlign:"center"},trialInfo:{fontSize:12,color:"#22c55e",fontWeight:"600",textAlign:"center"},featuresContainer:{marginBottom:24},featureItem:{flexDirection:"row",alignItems:"flex-start",marginBottom:12},featureCheckmark:{color:"#22c55e",fontSize:16,fontWeight:"700",marginRight:12,marginTop:2},featureText:{flex:1,fontSize:14,color:"#555",lineHeight:20},buttonContainer:{marginTop:"auto"},ctaButton:{paddingVertical:16,borderRadius:8},ctaButtonText:{fontSize:16,fontWeight:"600"},popularButton:{backgroundColor:"#007AFF"},popularButtonText:{color:"#ffffff"},regularButton:{backgroundColor:"#f8f9fa",borderWidth:1,borderColor:"#e0e0e0"},regularButtonText:{color:"#333"}});var ie=require("react"),_=require("react-native"),be=require("@stripe/stripe-react-native");var B=require("react/jsx-runtime"),Ee=({clientSecret:o,customerId:e,customerEmail:t,amount:r,currency:n="usd",description:i,metadata:d,onSuccess:c,onError:m,onLoading:b,containerStyle:P,showBillingDetails:g=!0})=>{let{confirmPayment:x}=(0,be.useStripe)(),{initialized:D}=H(),[s,S]=(0,ie.useState)(!1),[M,k]=(0,ie.useState)(t||""),[q,O]=(0,ie.useState)(""),[R,a]=(0,ie.useState)(""),[p,v]=(0,ie.useState)(!1),T=l=>{m?.(l),_.Alert.alert("Payment Error",l),console.error("Payment error:",l)},f=async()=>{if(!D){T(h.PROVIDER_NOT_CONFIGURED);return}if(g&&M&&!te(M)){T("Please enter a valid email address");return}if(!p){T("Please complete your card information");return}let l=o;if(!l&&r)try{let E=await fetch("/api/payments/create-payment-intent",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({amount:r,currency:n,customerId:e,description:i,metadata:d})});if(!E.ok)throw new Error("Failed to create payment intent");let{client_secret:W}=await E.json();l=W}catch{T("Failed to initialize payment");return}if(!l){T("Payment could not be initialized");return}S(!0),b?.(!0);try{let E=g?{email:M||void 0,name:q||void 0,phone:R||void 0}:void 0,{error:W,paymentIntent:pe}=await x(l,{paymentMethodType:"Card",paymentMethodData:{billingDetails:E}});if(W)throw new Error(W.message||h.PAYMENT_FAILED);if(pe?.status==="Succeeded")c?.(pe),_.Alert.alert("Success","Payment completed successfully!");else throw new Error("Payment was not completed")}catch(E){let W=E instanceof Error?E.message:h.PAYMENT_FAILED;T(W)}finally{S(!1),b?.(!1)}};return(0,B.jsx)(_.KeyboardAvoidingView,{behavior:_.Platform.OS==="ios"?"padding":"height",style:[K.container,P],children:(0,B.jsxs)(_.ScrollView,{showsVerticalScrollIndicator:!1,children:[g&&(0,B.jsxs)(_.View,{style:K.billingSection,children:[(0,B.jsx)(_.Text,{style:K.sectionTitle,children:"Billing Information"}),(0,B.jsxs)(_.View,{style:K.inputContainer,children:[(0,B.jsx)(_.Text,{style:K.inputLabel,children:"Email *"}),(0,B.jsx)(_.TextInput,{style:K.textInput,value:M,onChangeText:k,placeholder:"your@email.com",keyboardType:"email-address",autoCapitalize:"none",autoCorrect:!1})]}),(0,B.jsxs)(_.View,{style:K.inputContainer,children:[(0,B.jsx)(_.Text,{style:K.inputLabel,children:"Full Name"}),(0,B.jsx)(_.TextInput,{style:K.textInput,value:q,onChangeText:O,placeholder:"John Doe",autoCapitalize:"words"})]}),(0,B.jsxs)(_.View,{style:K.inputContainer,children:[(0,B.jsx)(_.Text,{style:K.inputLabel,children:"Phone"}),(0,B.jsx)(_.TextInput,{style:K.textInput,value:R,onChangeText:a,placeholder:"+1 (555) 123-4567",keyboardType:"phone-pad"})]})]}),(0,B.jsxs)(_.View,{style:K.cardSection,children:[(0,B.jsx)(_.Text,{style:K.sectionTitle,children:"Payment Information"}),(0,B.jsx)(_.View,{style:K.cardContainer,children:(0,B.jsx)(be.CardField,{postalCodeEnabled:!0,placeholders:{number:"4242 4242 4242 4242"},cardStyle:mt,style:K.cardFieldContainer,onCardChange:l=>{v(l.complete)}})})]}),(0,B.jsx)(_.TouchableOpacity,{style:[K.payButton,s&&K.payButtonDisabled],onPress:f,disabled:s||!p,activeOpacity:.8,children:s?(0,B.jsx)(_.ActivityIndicator,{color:"#ffffff",size:"small"}):(0,B.jsxs)(_.Text,{style:K.payButtonText,children:["Pay ",r?`$${(r/100).toFixed(2)}`:""]})})]})})},mt={backgroundColor:"#fafafa",textColor:"#333",fontSize:16,placeholderColor:"#999"},K=_.StyleSheet.create({container:{flex:1,padding:20,backgroundColor:"#ffffff"},billingSection:{marginBottom:24},cardSection:{marginBottom:32},sectionTitle:{fontSize:18,fontWeight:"600",color:"#333",marginBottom:16},inputContainer:{marginBottom:16},inputLabel:{fontSize:14,fontWeight:"500",color:"#555",marginBottom:8},textInput:{borderWidth:1,borderColor:"#ddd",borderRadius:8,paddingHorizontal:12,paddingVertical:12,fontSize:16,backgroundColor:"#fafafa"},cardContainer:{borderWidth:1,borderColor:"#ddd",borderRadius:8,backgroundColor:"#fafafa"},cardFieldContainer:{width:"100%",height:50},payButton:{backgroundColor:"#007AFF",paddingVertical:16,borderRadius:8,alignItems:"center",justifyContent:"center",minHeight:52},payButtonDisabled:{opacity:.5},payButtonText:{color:"#ffffff",fontSize:18,fontWeight:"600"}});var We=require("@stripe/stripe-react-native"),se=require("react-native");var Ge=require("react/jsx-runtime"),Ye=({customerId:o,amount:e,currency:t="usd",paymentIntentClientSecret:r,onSuccess:n,onError:i,children:d})=>{let{presentPaymentSheet:c,initPaymentSheet:m}=(0,We.useStripe)(),{initialized:b}=H(),P=async()=>{if(!b){i?.("Payment provider not initialized");return}try{if(r){let{error:x}=await m({merchantDisplayName:"Your App Name",paymentIntentClientSecret:r,defaultBillingDetails:{name:""},allowsDelayedPaymentMethods:!0});if(x)throw new Error(x.message)}let{error:g}=await c();if(g){if(g.code==="Canceled")return;throw new Error(g.message)}n?.({status:"succeeded"})}catch(g){let x=g instanceof Error?g.message:"Payment failed";i?.(x),se.Alert.alert("Payment Error",x)}};return(0,Ge.jsx)(se.View,{style:dt.container,children:d})},dt=se.StyleSheet.create({container:{flex:1}});var ge=require("react"),C=require("react-native");var w=require("react/jsx-runtime"),je=({subscription:o,onCancel:e,onReactivate:t,onUpdate:r,style:n})=>{let{activeSubscription:i,loading:d,error:c}=H(),[m,b]=(0,ge.useState)(null);(0,ge.useEffect)(()=>{b(o||i)},[o,i]);let P=()=>{m&&C.Alert.alert("Cancel Subscription","Are you sure you want to cancel your subscription? You will retain access until the end of your current billing period.",[{text:"Keep Subscription",style:"cancel"},{text:"Cancel",style:"destructive",onPress:()=>e?.(m.id)}])},g=()=>{m&&C.Alert.alert("Reactivate Subscription","Would you like to reactivate your subscription?",[{text:"No",style:"cancel"},{text:"Reactivate",onPress:()=>t?.(m.id)}])},x=M=>{switch(M){case"active":return"#10B981";case"trialing":return"#3B82F6";case"past_due":return"#F59E0B";case"canceled":return"#EF4444";default:return"#6B7280"}},D=M=>{switch(M){case"active":return"Active";case"trialing":return"Trial";case"past_due":return"Past Due";case"canceled":return"Canceled";default:return M}};if(d)return(0,w.jsx)(C.View,{style:[I.container,n],children:(0,w.jsx)(C.Text,{style:I.loadingText,children:"Loading subscription..."})});if(c)return(0,w.jsx)(C.View,{style:[I.container,n],children:(0,w.jsxs)(C.Text,{style:I.errorText,children:["Error: ",c.message]})});if(!m)return(0,w.jsx)(C.View,{style:[I.container,n],children:(0,w.jsx)(C.Text,{style:I.noSubscriptionText,children:"No active subscription"})});let s=m.status==="active"||m.status==="trialing",S=m.status==="canceled";return(0,w.jsxs)(C.ScrollView,{style:[I.container,n],children:[(0,w.jsxs)(C.View,{style:I.header,children:[(0,w.jsx)(C.Text,{style:I.title,children:"Subscription Details"}),(0,w.jsx)(C.View,{style:[I.statusBadge,{backgroundColor:x(m.status)}],children:(0,w.jsx)(C.Text,{style:I.statusText,children:D(m.status)})})]}),(0,w.jsxs)(C.View,{style:I.detailsContainer,children:[(0,w.jsxs)(C.View,{style:I.detailRow,children:[(0,w.jsx)(C.Text,{style:I.detailLabel,children:"Amount:"}),(0,w.jsx)(C.Text,{style:I.detailValue,children:Ce(m.amount||0,m.currency)})]}),(0,w.jsxs)(C.View,{style:I.detailRow,children:[(0,w.jsx)(C.Text,{style:I.detailLabel,children:"Billing Interval:"}),(0,w.jsx)(C.Text,{style:I.detailValue,children:m.interval})]}),(0,w.jsxs)(C.View,{style:I.detailRow,children:[(0,w.jsx)(C.Text,{style:I.detailLabel,children:"Current Period:"}),(0,w.jsxs)(C.Text,{style:I.detailValue,children:[me(m.currentPeriodStart)," -"," ",me(m.currentPeriodEnd)]})]}),m.trialEnd&&(0,w.jsxs)(C.View,{style:I.detailRow,children:[(0,w.jsx)(C.Text,{style:I.detailLabel,children:"Trial Ends:"}),(0,w.jsx)(C.Text,{style:I.detailValue,children:me(m.trialEnd)})]}),m.cancelAtPeriodEnd&&(0,w.jsx)(C.View,{style:I.warningContainer,children:(0,w.jsxs)(C.Text,{style:I.warningText,children:["Your subscription will cancel on"," ",me(m.currentPeriodEnd)]})})]}),(0,w.jsxs)(C.View,{style:I.actionsContainer,children:[s&&!m.cancelAtPeriodEnd&&(0,w.jsxs)(w.Fragment,{children:[(0,w.jsx)(C.TouchableOpacity,{style:I.primaryButton,onPress:()=>r?.(m.id),children:(0,w.jsx)(C.Text,{style:I.primaryButtonText,children:"Update Plan"})}),(0,w.jsx)(C.TouchableOpacity,{style:I.dangerButton,onPress:P,children:(0,w.jsx)(C.Text,{style:I.dangerButtonText,children:"Cancel Subscription"})})]}),m.cancelAtPeriodEnd&&(0,w.jsx)(C.TouchableOpacity,{style:I.primaryButton,onPress:g,children:(0,w.jsx)(C.Text,{style:I.primaryButtonText,children:"Reactivate Subscription"})}),S&&(0,w.jsx)(C.TouchableOpacity,{style:I.primaryButton,onPress:()=>r?.(m.id),children:(0,w.jsx)(C.Text,{style:I.primaryButtonText,children:"Subscribe Again"})})]})]})},I=C.StyleSheet.create({container:{flex:1,backgroundColor:"#FFFFFF",padding:16},header:{flexDirection:"row",justifyContent:"space-between",alignItems:"center",marginBottom:24},title:{fontSize:24,fontWeight:"bold",color:"#1F2937"},statusBadge:{paddingHorizontal:12,paddingVertical:6,borderRadius:16},statusText:{color:"#FFFFFF",fontSize:12,fontWeight:"600"},detailsContainer:{backgroundColor:"#F9FAFB",borderRadius:8,padding:16,marginBottom:24},detailRow:{flexDirection:"row",justifyContent:"space-between",alignItems:"center",paddingVertical:8,borderBottomWidth:1,borderBottomColor:"#E5E7EB"},detailLabel:{fontSize:14,color:"#6B7280",fontWeight:"500"},detailValue:{fontSize:14,color:"#1F2937",fontWeight:"600"},warningContainer:{backgroundColor:"#FEF3C7",borderRadius:8,padding:12,marginTop:16},warningText:{color:"#92400E",fontSize:14,textAlign:"center"},actionsContainer:{gap:12},primaryButton:{backgroundColor:"#3B82F6",borderRadius:8,padding:16,alignItems:"center"},primaryButtonText:{color:"#FFFFFF",fontSize:16,fontWeight:"600"},dangerButton:{backgroundColor:"#EF4444",borderRadius:8,padding:16,alignItems:"center"},dangerButtonText:{color:"#FFFFFF",fontSize:16,fontWeight:"600"},loadingText:{textAlign:"center",color:"#6B7280",fontSize:16},errorText:{textAlign:"center",color:"#EF4444",fontSize:16},noSubscriptionText:{textAlign:"center",color:"#6B7280",fontSize:16}});var we=require("react"),L=require("react-native"),qe=require("@stripe/stripe-react-native"),J=require("react/jsx-runtime"),Re=null;try{Re=require("react-native-touch-id")}catch{}var pt={title:"Authentication Required",imageColor:"#e00606",sensorDescription:"Touch sensor",sensorErrorDescription:"Failed",cancelText:"Cancel",fallbackLabel:"Show Passcode",unifiedErrors:!1,passcodeFallback:!1},He=({amount:o,currency:e="USD",paymentMethodId:t,clientSecret:r,onSuccess:n,onError:i,onCancel:d,title:c="Authorize Payment",subtitle:m,style:b})=>{let[P,g]=(0,we.useState)(!1),[x,D]=(0,we.useState)(!1),{confirmPayment:s}=(0,qe.useStripe)(),S=async()=>{try{return await Re.isSupported()!==!1}catch{return!1}},M=async()=>{try{return await Re.authenticate("Authenticate to complete your payment",pt),!0}catch(a){return a.name==="UserCancel"||a.name==="UserFallback"?d?.():i?.(`Authentication failed: ${a.message}`),!1}},k=async()=>{if(!r){i?.("Payment configuration is missing");return}D(!0);try{let{error:a,paymentIntent:p}=await s(r,{paymentMethodType:"Card"});if(a)throw new Error(a.message);n?.(p)}catch(a){let p=a instanceof Error?a.message:"Payment failed";i?.(p)}finally{D(!1)}},q=async()=>{g(!0);try{if(!await S()){L.Alert.alert("Biometric Authentication Not Available","Your device does not support biometric authentication. Please use an alternative payment method.",[{text:"OK",onPress:d}]);return}await M()&&await k()}catch(a){let p=a instanceof Error?a.message:"Authentication failed";i?.(p)}finally{g(!1)}},O=(a,p)=>new Intl.NumberFormat("en-US",{style:"currency",currency:p.toUpperCase()}).format(a/100),R=()=>L.Platform.OS==="ios"?"\u{1F446}":"\u{1F512}";return(0,J.jsx)(L.View,{style:[X.container,b],children:(0,J.jsxs)(L.View,{style:X.content,children:[(0,J.jsx)(L.Text,{style:X.title,children:c}),m&&(0,J.jsx)(L.Text,{style:X.subtitle,children:m}),(0,J.jsxs)(L.View,{style:X.amountContainer,children:[(0,J.jsx)(L.Text,{style:X.amountLabel,children:"Amount"}),(0,J.jsx)(L.Text,{style:X.amount,children:O(o,e)})]}),(0,J.jsxs)(L.TouchableOpacity,{style:[X.payButton,(P||x)&&X.payButtonDisabled],onPress:q,disabled:P||x,children:[(0,J.jsx)(L.Text,{style:X.biometricIcon,children:R()}),(0,J.jsx)(L.Text,{style:X.payButtonText,children:P?"Authenticating...":x?"Processing...":`Pay with ${L.Platform.OS==="ios"?"Touch ID":"Biometrics"}`})]}),(0,J.jsx)(L.Text,{style:X.securityNote,children:"Your payment information is secured with biometric authentication"})]})})},X=L.StyleSheet.create({container:{backgroundColor:"#FFFFFF",borderRadius:12,padding:20,margin:16,shadowColor:"#000",shadowOffset:{width:0,height:2},shadowOpacity:.1,shadowRadius:3.84,elevation:5},content:{alignItems:"center"},title:{fontSize:20,fontWeight:"bold",color:"#1F2937",marginBottom:8,textAlign:"center"},subtitle:{fontSize:14,color:"#6B7280",marginBottom:20,textAlign:"center"},amountContainer:{backgroundColor:"#F9FAFB",borderRadius:8,padding:16,marginBottom:24,minWidth:200,alignItems:"center"},amountLabel:{fontSize:12,color:"#6B7280",marginBottom:4},amount:{fontSize:24,fontWeight:"bold",color:"#1F2937"},payButton:{backgroundColor:"#3B82F6",borderRadius:8,paddingVertical:16,paddingHorizontal:32,flexDirection:"row",alignItems:"center",marginBottom:12},payButtonDisabled:{backgroundColor:"#9CA3AF"},biometricIcon:{fontSize:20,marginRight:8},payButtonText:{color:"#FFFFFF",fontSize:16,fontWeight:"600"},securityNote:{fontSize:12,color:"#6B7280",textAlign:"center",marginTop:8}});var Je=require("@stripe/stripe-react-native");var re=require("react-native"),oe=require("react/jsx-runtime"),Xe=({children:o,merchantIdentifier:e,urlScheme:t,publishableKey:r,setReturnUrlSchemeOnAndroid:n=!1})=>{let{config:i,initialized:d}=H();if(!d)return i?.environment==="development"?(0,oe.jsxs)(re.View,{style:Se.errorContainer,children:[(0,oe.jsx)(re.Text,{style:Se.errorTitle,children:"Payments Provider Error"}),(0,oe.jsx)(re.Text,{style:Se.errorMessage,children:h.PROVIDER_NOT_CONFIGURED}),(0,oe.jsx)(re.Text,{style:Se.errorSubtext,children:"Please check your PaymentsProvider configuration."})]}):null;let c=r||i?.publishableKey;return c?(0,oe.jsx)(Je.StripeProvider,{publishableKey:c,merchantIdentifier:e,urlScheme:t,setReturnUrlSchemeOnAndroid:n,children:o}):null},Se=re.StyleSheet.create({errorContainer:{padding:20,backgroundColor:"#fee",borderColor:"#fcc",borderWidth:1,borderRadius:4,margin:10},errorTitle:{fontWeight:"bold",fontSize:16,color:"#c53030",marginBottom:8},errorMessage:{fontSize:14,color:"#c53030",marginBottom:4},errorSubtext:{fontSize:12,color:"#a0a0a0"}});var U=require("react");var Ze=()=>{let[o,e]=(0,U.useState)(null),[t,r]=(0,U.useState)(null),[n,i]=(0,U.useState)(!1),[d,c]=(0,U.useState)(!1),[m,b]=(0,U.useState)(null),[P,g]=(0,U.useState)(null),[x,D]=(0,U.useState)([]),s=(0,U.useCallback)(N=>{b(N),console.error("Payments error:",N)},[]),S=(0,U.useCallback)(async(N,y)=>{if(!t)throw new u("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);c(!0),b(null);try{let Y=await t.listSubscriptions(N,y);D(Y)}catch(Y){throw s(Y),Y}finally{c(!1)}},[t,s]),M=(0,U.useCallback)(async N=>{c(!0),b(null);try{let y=N||z.autodetect(),Y=z.create(y);e(y),r(Y),i(!0)}catch(y){s(y)}finally{c(!1)}},[s]),k=(0,U.useCallback)(async N=>{if(!t)throw new u("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);c(!0),b(null);try{let y=await t.retrieveCustomer(N);return g(y),y}catch(y){throw s(y),y}finally{c(!1)}},[t,s]),q=(0,U.useCallback)(async N=>{if(!t)throw new u("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);c(!0),b(null);try{let y=await t.createCustomer(N);return g(y),y}catch(y){throw s(y),y}finally{c(!1)}},[t,s]),O=(0,U.useCallback)(async N=>{if(!t||!P)throw new u("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);c(!0),b(null);try{let y=await t.createSubscription({customerId:P.id,items:[{priceId:N.priceId,quantity:N.quantity}]});return await S(P.id),y}catch(y){throw s(y),y}finally{c(!1)}},[t,P,s,S]),R=(0,U.useCallback)(async(N,y)=>{if(!t)throw new u("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);c(!0),b(null);try{let Y=await t.listSubscriptions(N,y);return D(Y),Y}catch(Y){throw s(Y),Y}finally{c(!1)}},[t,s]),a=(0,U.useCallback)(async N=>{if(!t)throw new u("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);c(!0),b(null);try{let y=await t.retrieveSubscription(N);return P?.id&&await S(P.id),y}catch(y){throw s(y),y}finally{c(!1)}},[t,P,s,S]),p=(0,U.useCallback)(async N=>{if(!t)throw new u("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);c(!0),b(null);try{return await t.createCheckoutSession(N)}catch(y){throw s(y),y}finally{c(!1)}},[t,s]),v=(0,U.useCallback)(async N=>{if(!t)throw new u("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);c(!0),b(null);try{return await t.retrieveCheckoutSession(N)}catch(y){throw s(y),y}finally{c(!1)}},[t,s]),T=(0,U.useCallback)(async N=>{if(!t)throw new u("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);c(!0),b(null);try{await t.cancelSubscription(N),P?.id&&await S(P.id)}catch(y){throw s(y),y}finally{c(!1)}},[t,P,s,S]),f=(0,U.useCallback)(async N=>{if(!t)throw new u("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);c(!0),b(null);try{await t.reactivateSubscription(N),P?.id&&await S(P.id)}catch(y){throw s(y),y}finally{c(!1)}},[t,P,s,S]),l=(0,U.useCallback)(async(N,y)=>{if(!t)throw new u("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);c(!0),b(null);try{let Y=await t.updateSubscription(N,y);return P?.id&&await S(P.id),Y}catch(Y){throw s(Y),Y}finally{c(!1)}},[t,P,s,S]),E=(0,U.useCallback)(async N=>{if(!t)throw new u("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);c(!0),b(null);try{let y=await t.retrieveCustomer(N);g(y)}catch(y){throw s(y),y}finally{c(!1)}},[t,s]),W=(0,U.useCallback)(()=>{e(null),r(null),i(!1),c(!1),b(null),g(null),D([])},[]),pe=x.find(N=>N.status==="active"||N.status==="trialing")||null;return(0,U.useEffect)(()=>{},[]),{config:o,provider:t,initialized:n,loading:d,error:m,isLoading:d,isError:!!m,customer:P,subscriptions:x,activeSubscription:pe,initialize:M,createCustomer:q,retrieveCustomer:k,createCheckoutSession:p,retrieveCheckoutSession:v,createSubscription:O,cancelSubscription:T,reactivateSubscription:f,listSubscriptions:R,retrieveSubscription:a,updateSubscription:l,refreshCustomer:E,refreshSubscriptions:S,reset:W}};var j=require("react"),ae=require("react-native");var Qe=(o={})=>{let{customerId:e,subscriptionId:t,autoFetch:r=!0,onError:n,showErrorAlert:i=!0}=o,[d,c]=(0,j.useState)(null),[m,b]=(0,j.useState)([]),[P,g]=(0,j.useState)(!1),[x,D]=(0,j.useState)(null),s=(0,j.useCallback)(a=>{D(a),n?.(a),i&&ae.Alert.alert("Subscription Error",a),console.error("Subscription error:",a)},[n,i]),S=(0,j.useCallback)(async a=>{if(!G(a,"subscription"))return s("Invalid subscription ID"),null;try{let p=await fetch(`/api/payments/subscription/${a}`);if(!p.ok){let T=await p.json().catch(()=>({error:"Network error"}));throw new Error(T.error||h.SUBSCRIPTION_NOT_FOUND)}return await p.json()}catch(p){let v=p instanceof Error?p.message:h.SUBSCRIPTION_NOT_FOUND;return s(v),null}},[s]),M=(0,j.useCallback)(async a=>{if(!G(a,"customer"))return s("Invalid customer ID"),[];try{let p=await fetch(`/api/payments/customer/${a}/subscriptions`);if(!p.ok){let T=await p.json().catch(()=>({error:"Network error"}));throw new Error(T.error||h.CUSTOMER_NOT_FOUND)}return(await p.json()).subscriptions||[]}catch(p){let v=p instanceof Error?p.message:h.CUSTOMER_NOT_FOUND;return s(v),[]}},[s]),k=(0,j.useCallback)(async()=>{if(!e&&!t){s("Either customerId or subscriptionId is required");return}g(!0),D(null);try{if(t){let a=await S(t);c(a)}if(e){let a=await M(e);if(b(a),!t&&a.length>0){let p=a.find(v=>v.status==="active")||a[0];c(p)}}}finally{g(!1)}},[e,t,S,M,s]),q=(0,j.useCallback)(async a=>{let p=a||t;return p?G(p,"subscription")?new Promise(v=>{ae.Alert.alert("Cancel Subscription","Are you sure you want to cancel your subscription? It will remain active until the end of your current billing period.",[{text:"Keep Subscription",style:"cancel",onPress:()=>v(!1)},{text:"Cancel Subscription",style:"destructive",onPress:async()=>{try{let T=await fetch(`/api/payments/subscription/${p}/cancel`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!T.ok){let f=await T.json().catch(()=>({error:"Network error"}));throw new Error(f.error||"Failed to cancel subscription")}await k(),ae.Alert.alert("Success","Your subscription has been cancelled and will end at the end of your current billing period."),v(!0)}catch(T){let f=T instanceof Error?T.message:"Failed to cancel subscription";s(f),v(!1)}}}])}):(s("Invalid subscription ID"),!1):(s("Subscription ID is required to cancel"),!1)},[t,k,s]),O=(0,j.useCallback)(async a=>{let p=a||t;if(!p)return s("Subscription ID is required to reactivate"),!1;if(!G(p,"subscription"))return s("Invalid subscription ID"),!1;try{let v=await fetch(`/api/payments/subscription/${p}/reactivate`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!v.ok){let T=await v.json().catch(()=>({error:"Network error"}));throw new Error(T.error||"Failed to reactivate subscription")}return await k(),ae.Alert.alert("Success","Your subscription has been reactivated!"),!0}catch(v){let T=v instanceof Error?v.message:"Failed to reactivate subscription";return s(T),!1}},[t,k,s]),R=(0,j.useCallback)(async(a,p)=>{if(!G(a,"subscription"))return s("Invalid subscription ID"),!1;try{let v=await fetch(`/api/payments/subscription/${a}/payment-method`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({paymentMethodId:p})});if(!v.ok){let T=await v.json().catch(()=>({error:"Network error"}));throw new Error(T.error||"Failed to update payment method")}return await k(),ae.Alert.alert("Success","Payment method updated successfully!"),!0}catch(v){let T=v instanceof Error?v.message:"Failed to update payment method";return s(T),!1}},[k,s]);return(0,j.useEffect)(()=>{r&&(e||t)&&k()},[r,e,t,k]),{subscription:d,subscriptions:m,loading:P,error:x,isLoading:P,isError:!!x,refetch:k,cancel:q,reactivate:O,updatePaymentMethod:R}};var ee=require("react"),Ie=require("react-native"),et=require("@stripe/stripe-react-native");var Te=(o={})=>{let{onSuccess:e,onError:t,onLoading:r,showErrorAlert:n=!0,showSuccessAlert:i=!0}=o,{initPaymentSheet:d,presentPaymentSheet:c,confirmPayment:m}=(0,et.useStripe)(),{initialized:b}=H(),[P,g]=(0,ee.useState)(!1),[x,D]=(0,ee.useState)(null),s=(0,ee.useCallback)(O=>{D(O),t?.(O),n&&Ie.Alert.alert("Payment Error",O),console.error("Checkout error:",O)},[t,n]),S=(0,ee.useCallback)(O=>{e?.(O),i&&Ie.Alert.alert("Success","Payment completed successfully!")},[e,i]),M=(0,ee.useCallback)(async O=>{if(!b)return s(h.PROVIDER_NOT_CONFIGURED),!1;if(!G(O.priceId,"price"))return s(h.INVALID_PRICE_ID),!1;if(O.customerId&&!G(O.customerId,"customer"))return s(h.INVALID_CUSTOMER_ID),!1;if(O.customerEmail&&!te(O.customerEmail))return s("Invalid customer email"),!1;g(!0),D(null),r?.(!0);try{let R=await fetch("/api/payments/create-subscription-setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(O)});if(!R.ok){let l=await R.json().catch(()=>({error:"Network error"}));throw new Error(l.error||"Failed to create subscription setup")}let{setupIntentClientSecret:a,customerId:p,customerEphemeralKeySecret:v}=await R.json();if(!a)throw new Error("No setup intent client secret returned from server");let{error:T}=await d({setupIntentClientSecret:a,customerId:p,customerEphemeralKeySecret:v,merchantDisplayName:"Your App Name",allowsDelayedPaymentMethods:!0});if(T)throw new Error(T.message||"Failed to initialize payment sheet");let{error:f}=await c();if(f){if(f.code==="Canceled")return!1;throw new Error(f.message||h.PAYMENT_FAILED)}return S({type:"subscription",customerId:p}),!0}catch(R){let a=R instanceof Error?R.message:"Failed to create subscription";return s(a),!1}finally{g(!1),r?.(!1)}},[b,d,c,s,S,r]),k=(0,ee.useCallback)(async O=>{if(!b)return s(h.PROVIDER_NOT_CONFIGURED),null;if(O.amount<=0)return s("Amount must be greater than 0"),null;if(O.customerId&&!G(O.customerId,"customer"))return s(h.INVALID_CUSTOMER_ID),null;g(!0),D(null),r?.(!0);try{let R=await fetch("/api/payments/create-payment-intent",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(O)});if(!R.ok){let p=await R.json().catch(()=>({error:"Network error"}));throw new Error(p.error||"Failed to create payment intent")}let{client_secret:a}=await R.json();if(!a)throw new Error("No client secret returned from server");return a}catch(R){let a=R instanceof Error?R.message:"Failed to create payment intent";return s(a),null}finally{g(!1),r?.(!1)}},[b,s,r]),q=(0,ee.useCallback)(async(O,R)=>{if(!b)return s(h.PROVIDER_NOT_CONFIGURED),!1;if(R?.email&&!te(R.email))return s("Invalid email address"),!1;g(!0),D(null),r?.(!0);try{let{error:a,paymentIntent:p}=await m(O,{paymentMethodType:"Card",paymentMethodData:{billingDetails:R}});if(a)throw new Error(a.message||h.PAYMENT_FAILED);if(p?.status==="Succeeded")return S({type:"payment",paymentIntent:p}),!0;throw new Error("Payment was not completed")}catch(a){let p=a instanceof Error?a.message:h.PAYMENT_FAILED;return s(p),!1}finally{g(!1),r?.(!1)}},[b,m,s,S,r]);return{loading:P,error:x,isLoading:P,isError:!!x,createSubscription:M,createPaymentIntent:k,processPayment:q}};var $=require("react"),de=require("react-native");var tt=(o={})=>{let{customerId:e,autoFetch:t=!0,onError:r,showErrorAlert:n=!0,showSuccessAlert:i=!0}=o,[d,c]=(0,$.useState)(null),[m,b]=(0,$.useState)([]),[P,g]=(0,$.useState)(!1),[x,D]=(0,$.useState)(null),s=(0,$.useCallback)(f=>{D(f),r?.(f),n&&de.Alert.alert("Customer Error",f),console.error("Customer error:",f)},[r,n]),S=(0,$.useCallback)(f=>{i&&de.Alert.alert("Success",f)},[i]),M=(0,$.useCallback)(async f=>{if(!G(f,"customer"))return s("Invalid customer ID"),null;try{let l=await fetch(`/api/payments/customer/${f}`);if(!l.ok){let W=await l.json().catch(()=>({error:"Network error"}));throw new Error(W.error||h.CUSTOMER_NOT_FOUND)}return await l.json()}catch(l){let E=l instanceof Error?l.message:h.CUSTOMER_NOT_FOUND;return s(E),null}},[s]),k=(0,$.useCallback)(async()=>{if(!e){s("Customer ID is required");return}g(!0),D(null);try{let f=await M(e);c(f)}finally{g(!1)}},[e,M,s]),q=(0,$.useCallback)(async f=>{if(!te(f.email))return s("Invalid email address"),null;g(!0),D(null);try{let l=await fetch("/api/payments/customer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f)});if(!l.ok){let W=await l.json().catch(()=>({error:"Network error"}));throw new Error(W.error||"Failed to create customer")}let E=await l.json();return c(E),S("Customer created successfully!"),E}catch(l){let E=l instanceof Error?l.message:"Failed to create customer";return s(E),null}finally{g(!1)}},[s,S]),O=(0,$.useCallback)(async f=>{if(!e)return s("Customer ID is required"),!1;if(f.email&&!te(f.email))return s("Invalid email address"),!1;g(!0),D(null);try{let l=await fetch(`/api/payments/customer/${e}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(f)});if(!l.ok){let E=await l.json().catch(()=>({error:"Network error"}));throw new Error(E.error||"Failed to update customer")}return await k(),S("Customer updated successfully!"),!0}catch(l){let E=l instanceof Error?l.message:"Failed to update customer";return s(E),!1}finally{g(!1)}},[e,k,s,S]),R=(0,$.useCallback)(async()=>e?new Promise(f=>{de.Alert.alert("Delete Customer","Are you sure you want to delete this customer? This action cannot be undone.",[{text:"Cancel",style:"cancel",onPress:()=>f(!1)},{text:"Delete",style:"destructive",onPress:async()=>{g(!0),D(null);try{let l=await fetch(`/api/payments/customer/${e}`,{method:"DELETE"});if(!l.ok){let E=await l.json().catch(()=>({error:"Network error"}));throw new Error(E.error||"Failed to delete customer")}c(null),b([]),S("Customer deleted successfully!"),f(!0)}catch(l){let E=l instanceof Error?l.message:"Failed to delete customer";s(E),f(!1)}finally{g(!1)}}}])}):(s("Customer ID is required"),!1),[e,s,S]),a=(0,$.useCallback)(async()=>{if(!e)return s("Customer ID is required"),[];try{let f=await fetch(`/api/payments/customer/${e}/payment-methods`);if(!f.ok){let W=await f.json().catch(()=>({error:"Network error"}));throw new Error(W.error||"Failed to fetch payment methods")}let E=(await f.json()).paymentMethods||[];return b(E),E}catch(f){let l=f instanceof Error?f.message:"Failed to fetch payment methods";return s(l),[]}},[e,s]),p=(0,$.useCallback)(async f=>{if(!e)return s("Customer ID is required"),!1;try{let l=await fetch(`/api/payments/customer/${e}/payment-methods`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paymentMethodId:f})});if(!l.ok){let E=await l.json().catch(()=>({error:"Network error"}));throw new Error(E.error||"Failed to add payment method")}return await a(),S("Payment method added successfully!"),!0}catch(l){let E=l instanceof Error?l.message:"Failed to add payment method";return s(E),!1}},[e,a,s,S]),v=(0,$.useCallback)(async f=>e?new Promise(l=>{de.Alert.alert("Remove Payment Method","Are you sure you want to remove this payment method?",[{text:"Cancel",style:"cancel",onPress:()=>l(!1)},{text:"Remove",style:"destructive",onPress:async()=>{try{let E=await fetch(`/api/payments/customer/${e}/payment-methods/${f}`,{method:"DELETE"});if(!E.ok){let W=await E.json().catch(()=>({error:"Network error"}));throw new Error(W.error||"Failed to remove payment method")}await a(),S("Payment method removed successfully!"),l(!0)}catch(E){let W=E instanceof Error?E.message:"Failed to remove payment method";s(W),l(!1)}}}])}):(s("Customer ID is required"),!1),[e,a,s,S]),T=(0,$.useCallback)(async f=>{if(!e)return s("Customer ID is required"),!1;try{let l=await fetch(`/api/payments/customer/${e}/default-payment-method`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({paymentMethodId:f})});if(!l.ok){let E=await l.json().catch(()=>({error:"Network error"}));throw new Error(E.error||"Failed to set default payment method")}return await Promise.all([k(),a()]),S("Default payment method updated successfully!"),!0}catch(l){let E=l instanceof Error?l.message:"Failed to set default payment method";return s(E),!1}},[e,k,a,s,S]);return(0,$.useEffect)(()=>{t&&e&&(k(),a())},[t,e,k,a]),{customer:d,paymentMethods:m,loading:P,error:x,isLoading:P,isError:!!x,refetch:k,createCustomer:q,updateCustomer:O,deleteCustomer:R,fetchPaymentMethods:a,addPaymentMethod:p,removePaymentMethod:v,setDefaultPaymentMethod:T}};var ft=async o=>{try{let e=await fetch("/api/payments/create-subscription-setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!e.ok)return{error:(await e.json().catch(()=>({error:"Network error"}))).error||"Failed to create subscription setup"};let t=await e.json();return{setupIntentClientSecret:t.setupIntentClientSecret,customerId:t.customerId,customerEphemeralKeySecret:t.customerEphemeralKeySecret}}catch(e){return{error:e instanceof Error?e.message:"Failed to create subscription setup"}}},yt=async o=>{try{let e=await fetch("/api/payments/create-payment-intent",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});return e.ok?{clientSecret:(await e.json()).client_secret}:{error:(await e.json().catch(()=>({error:"Network error"}))).error||"Failed to create payment intent"}}catch(e){return{error:e instanceof Error?e.message:"Failed to create payment intent"}}},ht=o=>{let e=[];return o.publishableKey||e.push("publishableKey is required"),o.provider||e.push("provider is required"),o.provider!=="stripe"&&e.push("Only stripe provider is currently supported"),o.environment||e.push("environment is required"),o.environment&&!["development","production"].includes(o.environment)&&e.push('environment must be either "development" or "production"'),o.publishableKey&&!o.publishableKey.startsWith("pk_")&&e.push('publishableKey must start with "pk_"'),{isValid:e.length===0,errors:e}},Pt=o=>{if(typeof o=="string")return o;if(typeof o=="object"&&o!==null){if("message"in o&&typeof o.message=="string")return o.message;if("code"in o&&typeof o.code=="string"){let e=o.code;return{Canceled:"Payment was cancelled",Failed:"Payment failed",card_declined:"Your card was declined.",expired_card:"Your card has expired.",incorrect_cvc:"Your card's security code is incorrect.",processing_error:"An error occurred while processing your card.",incorrect_number:"Your card number is incorrect."}[e]||`Payment failed: ${e}`}}return"An unexpected error occurred."},bt=async o=>{try{let e=await fetch("/api/payments/customer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});return e.ok?{customer:await e.json()}:{error:(await e.json().catch(()=>({error:"Network error"}))).error||"Failed to create customer"}}catch(e){return{error:e instanceof Error?e.message:"Failed to create customer"}}},gt=async o=>{try{let e=await fetch(`/api/payments/subscription/${o}`);return e.ok?{subscription:await e.json()}:{error:(await e.json().catch(()=>({error:"Network error"}))).error||h.SUBSCRIPTION_NOT_FOUND}}catch(e){return{error:e instanceof Error?e.message:h.SUBSCRIPTION_NOT_FOUND}}},St=async o=>{try{let e=await fetch(`/api/payments/customer/${o}/subscriptions`);return e.ok?{subscriptions:(await e.json()).subscriptions||[]}:{error:(await e.json().catch(()=>({error:"Network error"}))).error||h.CUSTOMER_NOT_FOUND}}catch(e){return{error:e instanceof Error?e.message:h.CUSTOMER_NOT_FOUND}}},Ct=async o=>{try{let e=await fetch(`/api/payments/subscription/${o}/cancel`,{method:"POST",headers:{"Content-Type":"application/json"}});return e.ok?{success:!0}:{success:!1,error:(await e.json().catch(()=>({error:"Network error"}))).error||"Failed to cancel subscription"}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Failed to cancel subscription"}}};0&&(module.exports={CheckoutButton,CheckoutForm,MobilePaymentSheet,NativeSubscriptionView,PaymentForm,PaymentsProvider,PricingTable,StripeProvider,TouchIDPayment,cancelSubscription,createCustomer,createPaymentIntent,createSubscriptionSetup,fetchCustomerSubscriptions,fetchSubscription,formatStripeError,useCheckout,useCustomer,usePayments,usePaymentsContext,useStripe,useSubscription,validatePaymentsConfig});
|
|
2
|
+
"use strict";var ye=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var Ge=Object.getOwnPropertyNames;var Ke=Object.prototype.hasOwnProperty;var Ye=(t,e)=>{for(var o in e)ye(t,o,{get:e[o],enumerable:!0})},He=(t,e,o,u)=>{if(e&&typeof e=="object"||typeof e=="function")for(let l of Ge(e))!Ke.call(t,l)&&l!==o&&ye(t,l,{get:()=>e[l],enumerable:!(u=We(e,l))||u.enumerable});return t};var qe=t=>He(ye({},"__esModule",{value:!0}),t);var ct={};Ye(ct,{CheckoutButton:()=>me,CheckoutForm:()=>ge,MobilePaymentSheet:()=>Ae,NativeSubscriptionView:()=>Ue,PaymentForm:()=>ge,PaymentsProvider:()=>Re,PricingTable:()=>Fe,StripeProvider:()=>Le,TouchIDPayment:()=>Me,cancelSubscription:()=>at,createCustomer:()=>nt,createPaymentIntent:()=>tt,createSubscriptionSetup:()=>et,fetchCustomerSubscriptions:()=>it,fetchSubscription:()=>st,formatStripeError:()=>ot,useCheckout:()=>Ce,useCustomer:()=>ze,usePayments:()=>le,usePaymentsContext:()=>Y,useStripe:()=>Ce,useSubscription:()=>je,validatePaymentsConfig:()=>rt});module.exports=qe(ct);var Oe=require("react"),Z=require("react-native"),Ne=require("@stripe/stripe-react-native");var J=require("react");var M=require("react");var v=class t extends Error{type;code;details;constructor(e,o,u,l){super(o),this.name="PaymentsError",this.type=e,this.code=u,this.details=l,Object.setPrototypeOf(this,t.prototype)}};var Pe={USD:"$",EUR:"\u20AC",GBP:"\xA3",JPY:"\xA5",CAD:"C$",AUD:"A$",CHF:"CHF",CNY:"\xA5",SEK:"kr",NZD:"NZ$"},we="USD";var h={PROVIDER_NOT_CONFIGURED:"Payments provider is not properly configured",STRIPE_NOT_LOADED:"Stripe has not been loaded yet",INVALID_PRICE_ID:"Invalid price ID provided",INVALID_CUSTOMER_ID:"Invalid customer ID provided",CHECKOUT_FAILED:"Checkout session creation failed",PAYMENT_FAILED:"Payment processing failed",SUBSCRIPTION_NOT_FOUND:"Subscription not found",CUSTOMER_NOT_FOUND:"Customer not found"};var le=()=>{let[t,e]=(0,M.useState)(null),[o,u]=(0,M.useState)(!1),[l,i]=(0,M.useState)(!1),[E,m]=(0,M.useState)(null),[s,I]=(0,M.useState)(null),[O,g]=(0,M.useState)([]),d=(0,M.useCallback)(y=>{let a=y instanceof v?y:new v("UNKNOWN_ERROR",y.message);m(a),console.error("Payments error:",a)},[]),A=(0,M.useCallback)(async y=>{i(!0),m(null);try{if(!y)throw new v("CONFIGURATION_ERROR","Configuration is required for native initialization");e(y),u(!0)}catch(a){d(a)}finally{i(!1)}},[d]),r=(0,M.useCallback)(async(y,a)=>{if(!o)throw new v("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);i(!0),m(null);try{let _=await fetch(`/api/payments/subscriptions?customerId=${y}${a?`&status=${a}`:""}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!_.ok)throw new v("NETWORK_ERROR","Failed to fetch subscriptions");let re=await _.json();g(re)}catch(_){throw d(_),_}finally{i(!1)}},[o,d]),w=(0,M.useCallback)(async y=>{if(!o)throw new v("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);i(!0),m(null);try{let a=await fetch(`/api/payments/customers/${y}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!a.ok)throw new v("NETWORK_ERROR","Failed to retrieve customer");let _=await a.json();return I(_),_}catch(a){throw d(a),a}finally{i(!1)}},[o,d]),V=(0,M.useCallback)(async y=>{if(!o)throw new v("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);i(!0),m(null);try{let a=await fetch("/api/payments/customers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(y)});if(!a.ok)throw new v("NETWORK_ERROR","Failed to create customer");let _=await a.json();return I(_),_}catch(a){throw d(a),a}finally{i(!1)}},[o,d]),F=(0,M.useCallback)(async y=>{if(!o||!s)throw new v("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);i(!0),m(null);try{let a=await fetch("/api/payments/subscriptions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({customerId:s.id,items:[{priceId:y.priceId,quantity:y.quantity}]})});if(!a.ok)throw new v("NETWORK_ERROR","Failed to create subscription");let _=await a.json();return await r(s.id),_}catch(a){throw d(a),a}finally{i(!1)}},[o,s,d,r]),K=(0,M.useCallback)(async(y,a)=>{if(!o)throw new v("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);i(!0),m(null);try{let _=await fetch(`/api/payments/subscriptions?customerId=${y}${a?`&status=${a}`:""}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!_.ok)throw new v("NETWORK_ERROR","Failed to list subscriptions");let re=await _.json();return g(re),re}catch(_){throw d(_),_}finally{i(!1)}},[o,d]),N=(0,M.useCallback)(async y=>{if(!o)throw new v("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);i(!0),m(null);try{let a=await fetch(`/api/payments/subscriptions/${y}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!a.ok)throw new v("NETWORK_ERROR","Failed to retrieve subscription");let _=await a.json();return s?.id&&await r(s.id),_}catch(a){throw d(a),a}finally{i(!1)}},[o,s,d,r]),P=(0,M.useCallback)(async y=>{if(!o)throw new v("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);i(!0),m(null);try{let a=await fetch("/api/payments/checkout-sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(y)});if(!a.ok)throw new v("NETWORK_ERROR","Failed to create checkout session");return await a.json()}catch(a){throw d(a),a}finally{i(!1)}},[o,d]),n=(0,M.useCallback)(async y=>{if(!o)throw new v("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);i(!0),m(null);try{let a=await fetch(`/api/payments/checkout-sessions/${y}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!a.ok)throw new v("NETWORK_ERROR","Failed to retrieve checkout session");return await a.json()}catch(a){throw d(a),a}finally{i(!1)}},[o,d]),p=(0,M.useCallback)(async y=>{if(!o)throw new v("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);i(!0),m(null);try{if(!(await fetch(`/api/payments/subscriptions/${y}/cancel`,{method:"POST",headers:{"Content-Type":"application/json"}})).ok)throw new v("NETWORK_ERROR","Failed to cancel subscription");s?.id&&await r(s.id)}catch(a){throw d(a),a}finally{i(!1)}},[o,s,d,r]),D=(0,M.useCallback)(async y=>{if(!o)throw new v("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);i(!0),m(null);try{if(!(await fetch(`/api/payments/subscriptions/${y}/reactivate`,{method:"POST",headers:{"Content-Type":"application/json"}})).ok)throw new v("NETWORK_ERROR","Failed to reactivate subscription");s?.id&&await r(s.id)}catch(a){throw d(a),a}finally{i(!1)}},[o,s,d,r]),T=(0,M.useCallback)(async(y,a)=>{if(!o)throw new v("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);i(!0),m(null);try{let _=await fetch(`/api/payments/subscriptions/${y}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!_.ok)throw new v("NETWORK_ERROR","Failed to update subscription");let re=await _.json();return s?.id&&await r(s.id),re}catch(_){throw d(_),_}finally{i(!1)}},[o,s,d,r]),f=(0,M.useCallback)(async y=>{if(!o)throw new v("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);i(!0),m(null);try{let a=await fetch(`/api/payments/customers/${y}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!a.ok)throw new v("NETWORK_ERROR","Failed to refresh customer");let _=await a.json();I(_)}catch(a){throw d(a),a}finally{i(!1)}},[o,d]),c=(0,M.useCallback)(()=>{e(null),u(!1),i(!1),m(null),I(null),g([])},[]),S=O.find(y=>y.status==="active"||y.status==="trialing")||null;return{config:t,initialized:o,loading:l,error:E,isLoading:l,isError:!!E,customer:s,subscriptions:O,activeSubscription:S,initialize:A,createCustomer:V,retrieveCustomer:w,createCheckoutSession:P,retrieveCheckoutSession:n,createSubscription:F,cancelSubscription:p,reactivateSubscription:D,listSubscriptions:K,retrieveSubscription:N,updateSubscription:T,refreshCustomer:f,refreshSubscriptions:r,reset:c}};var Te=require("react/jsx-runtime"),Ie=(0,J.createContext)(void 0),Re=({children:t,config:e,onPaymentSuccess:o,onPaymentError:u})=>{let l=le(),{initialize:i,initialized:E,loading:m,error:s,customer:I,subscriptions:O,activeSubscription:g}=l,d=(0,J.useRef)(o),A=(0,J.useRef)(u);(0,J.useEffect)(()=>{d.current=o},[o]),(0,J.useEffect)(()=>{A.current=u},[u]),(0,J.useEffect)(()=>{!E&&!m&&!s&&e&&i(e).catch(w=>{console.error("PaymentsProvider initialization failed:",w),A.current&&A.current(w)})},[E,m,s,e,i]);let r={config:l.config,initialized:E,loading:m,error:s,customer:I,subscriptions:O,activeSubscription:g,createCustomer:l.createCustomer,createCheckoutSession:l.createCheckoutSession,cancelSubscription:l.cancelSubscription,reactivateSubscription:l.reactivateSubscription,updateSubscription:l.updateSubscription,refreshCustomer:l.refreshCustomer,refreshSubscriptions:l.refreshSubscriptions,reset:l.reset};return(0,Te.jsx)(Ie.Provider,{value:r,children:t})},Y=()=>{let t=(0,J.useContext)(Ie);if(t===void 0)throw new Error("usePaymentsContext must be used within a PaymentsProvider");return t};var X=t=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t);var W=(t,e)=>{let o={customer:"cus_",subscription:"sub_",price:"price_",product:"prod_",payment_intent:"pi_"};return t.startsWith(o[e])};var ae=require("react/jsx-runtime"),me=({priceId:t,customerId:e,customerEmail:o,children:u,style:l,textStyle:i,disabled:E=!1,metadata:m,trialPeriodDays:s,onSuccess:I,onError:O,onLoading:g})=>{let{initPaymentSheet:d,presentPaymentSheet:A}=(0,Ne.useStripe)(),{initialized:r}=Y(),[w,V]=(0,Oe.useState)(!1),F=P=>{O?.(P),Z.Alert.alert("Payment Error",P),console.error("Checkout error:",P)},K=async()=>{if(!r){F(h.PROVIDER_NOT_CONFIGURED);return}if(!W(t,"price")){F(h.INVALID_PRICE_ID);return}if(e&&!W(e,"customer")){F(h.INVALID_CUSTOMER_ID);return}V(!0),g?.(!0);try{let P=await fetch("/api/payments/create-subscription-setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({priceId:t,customerId:e,customerEmail:o,metadata:m,trialPeriodDays:s})});if(!P.ok){let c=await P.json().catch(()=>({error:"Network error"}));throw new Error(c.error||h.CHECKOUT_FAILED)}let{setupIntentClientSecret:n,customerId:p,customerEphemeralKeySecret:D}=await P.json();if(!n)throw new Error("No setup intent client secret returned from server");let{error:T}=await d({setupIntentClientSecret:n,customerId:p,customerEphemeralKeySecret:D,merchantDisplayName:"Your App Name",allowsDelayedPaymentMethods:!0});if(T)throw new Error(T.message||"Failed to initialize payment sheet");let{error:f}=await A();if(f){if(f.code!=="Canceled")throw new Error(f.message||h.PAYMENT_FAILED);return}I?.()}catch(P){let n=P instanceof Error?P.message:h.CHECKOUT_FAILED;F(n)}finally{V(!1),g?.(!1)}},N=w||E||!r;return(0,ae.jsxs)(Z.TouchableOpacity,{style:[ie.button,l,N&&ie.disabled],onPress:K,disabled:N,activeOpacity:.8,children:[w?(0,ae.jsx)(Z.ActivityIndicator,{color:"#ffffff",size:"small",style:ie.loader}):null,(0,ae.jsx)(Z.Text,{style:[ie.buttonText,i,w&&ie.loadingText],children:w?"Processing...":u})]})},ie=Z.StyleSheet.create({button:{backgroundColor:"#007AFF",paddingHorizontal:16,paddingVertical:12,borderRadius:8,flexDirection:"row",alignItems:"center",justifyContent:"center",minHeight:48},buttonText:{color:"#ffffff",fontSize:16,fontWeight:"600",textAlign:"center"},disabled:{opacity:.5},loader:{marginRight:8},loadingText:{marginLeft:8}});var U=require("react-native");var he=(t,e=we,o={})=>{let{showSymbol:u=!0,showCents:l=!0,locale:i="en-US"}=o,E=e.toUpperCase(),m=["JPY","KRW","VND","CLP"].includes(E),s=m?t:t/100;if(u)try{return new Intl.NumberFormat(i,{style:"currency",currency:E,minimumFractionDigits:l&&!m?2:0,maximumFractionDigits:l&&!m?2:0}).format(s)}catch{let I=Pe[E]||E,O=l&&!m?s.toFixed(2):Math.round(s).toString();return`${I}${O}`}return l&&!m?s.toFixed(2):Math.round(s).toString()},De=t=>{let e=he(t.price,t.currency),o=t.intervalCount&&t.intervalCount>1?`${t.intervalCount} ${t.interval}s`:t.interval;return`${e}/${o}`};var ce=(t,e={})=>{let{format:o="medium",locale:u="en-US",timeZone:l}=e,i=typeof t=="string"||typeof t=="number"?new Date(t):t,E={timeZone:l};switch(o){case"short":E.dateStyle="short";break;case"medium":E.dateStyle="medium";break;case"long":E.dateStyle="long";break;case"full":E.dateStyle="full";break}try{return new Intl.DateTimeFormat(u,E).format(i)}catch{return i.toLocaleDateString()}};var xe=t=>t===0?"No trial":t===1?"1 day trial":t<7?`${t} days trial`:t===7?"1 week trial":t<30?`${Math.floor(t/7)} weeks trial`:t===30?"1 month trial":`${Math.floor(t/30)} months trial`;var B=require("react/jsx-runtime"),{width:_e}=U.Dimensions.get("window"),Fe=({plans:t,customerId:e,customerEmail:o,onCheckoutSuccess:u,onCheckoutError:l,showFeatures:i=!0,showTrialInfo:E=!0,layout:m="carousel",containerStyle:s})=>{if(!t||t.length===0)return(0,B.jsx)(U.View,{style:k.emptyContainer,children:(0,B.jsx)(U.Text,{style:k.emptyText,children:"No pricing plans available"})});let I=O=>(0,B.jsx)(Je,{plan:O,customerId:e,customerEmail:o,onCheckoutSuccess:()=>u?.(O),onCheckoutError:g=>l?.(O,g),showFeatures:i,showTrialInfo:E,style:m==="carousel"?k.carouselCard:k.listCard},O.id);return m==="carousel"?(0,B.jsx)(U.View,{style:[k.container,s],children:(0,B.jsx)(U.ScrollView,{horizontal:!0,showsHorizontalScrollIndicator:!1,contentContainerStyle:k.carouselContainer,snapToInterval:_e*.8+16,decelerationRate:"fast",children:t.map(I)})}):(0,B.jsx)(U.ScrollView,{style:[k.container,s],children:(0,B.jsx)(U.View,{style:k.listContainer,children:t.map(I)})})},Je=({plan:t,customerId:e,customerEmail:o,onCheckoutSuccess:u,onCheckoutError:l,showFeatures:i=!0,showTrialInfo:E=!0,style:m})=>{let s=t.popular;return(0,B.jsxs)(U.View,{style:[k.card,s&&k.popularCard,m],children:[s&&(0,B.jsx)(U.View,{style:k.popularBadge,children:(0,B.jsx)(U.Text,{style:k.popularBadgeText,children:"Most Popular"})}),(0,B.jsxs)(U.View,{style:k.cardHeader,children:[(0,B.jsx)(U.Text,{style:k.planName,children:t.name}),t.description&&(0,B.jsx)(U.Text,{style:k.planDescription,children:t.description}),(0,B.jsx)(U.Text,{style:k.planPrice,children:De(t)}),E&&t.trialPeriodDays&&t.trialPeriodDays>0&&(0,B.jsx)(U.Text,{style:k.trialInfo,children:xe(t.trialPeriodDays)})]}),i&&t.features&&t.features.length>0&&(0,B.jsx)(U.View,{style:k.featuresContainer,children:t.features.map((I,O)=>(0,B.jsxs)(U.View,{style:k.featureItem,children:[(0,B.jsx)(U.Text,{style:k.featureCheckmark,children:"\u2713"}),(0,B.jsx)(U.Text,{style:k.featureText,children:I})]},O))}),(0,B.jsx)(U.View,{style:k.buttonContainer,children:(0,B.jsx)(me,{priceId:t.stripePriceId,customerId:e,customerEmail:o,trialPeriodDays:t.trialPeriodDays,metadata:t.metadata,onSuccess:u,onError:l,style:[k.ctaButton,s?k.popularButton:k.regularButton],textStyle:[k.ctaButtonText,s?k.popularButtonText:k.regularButtonText],children:"Get Started"})})]})},k=U.StyleSheet.create({container:{flex:1},emptyContainer:{flex:1,justifyContent:"center",alignItems:"center",padding:20},emptyText:{fontSize:16,color:"#666",textAlign:"center"},carouselContainer:{paddingHorizontal:16},listContainer:{padding:16},carouselCard:{width:_e*.8,marginRight:16},listCard:{marginBottom:16},card:{backgroundColor:"#ffffff",borderRadius:12,padding:20,shadowColor:"#000",shadowOffset:{width:0,height:2},shadowOpacity:.1,shadowRadius:8,elevation:4,borderWidth:1,borderColor:"#e0e0e0"},popularCard:{borderColor:"#007AFF",borderWidth:2},popularBadge:{position:"absolute",top:-1,left:-1,right:-1,backgroundColor:"#007AFF",paddingVertical:8,borderTopLeftRadius:12,borderTopRightRadius:12,alignItems:"center"},popularBadgeText:{color:"#ffffff",fontSize:12,fontWeight:"600"},cardHeader:{alignItems:"center",marginBottom:20,marginTop:20},planName:{fontSize:20,fontWeight:"700",color:"#333",marginBottom:8,textAlign:"center"},planDescription:{fontSize:14,color:"#666",textAlign:"center",marginBottom:16,lineHeight:20},planPrice:{fontSize:28,fontWeight:"800",color:"#333",marginBottom:8,textAlign:"center"},trialInfo:{fontSize:12,color:"#22c55e",fontWeight:"600",textAlign:"center"},featuresContainer:{marginBottom:24},featureItem:{flexDirection:"row",alignItems:"flex-start",marginBottom:12},featureCheckmark:{color:"#22c55e",fontSize:16,fontWeight:"700",marginRight:12,marginTop:2},featureText:{flex:1,fontSize:14,color:"#555",lineHeight:20},buttonContainer:{marginTop:"auto"},ctaButton:{paddingVertical:16,borderRadius:8},ctaButtonText:{fontSize:16,fontWeight:"600"},popularButton:{backgroundColor:"#007AFF"},popularButtonText:{color:"#ffffff"},regularButton:{backgroundColor:"#f8f9fa",borderWidth:1,borderColor:"#e0e0e0"},regularButtonText:{color:"#333"}});var oe=require("react"),x=require("react-native"),de=require("@stripe/stripe-react-native");var L=require("react/jsx-runtime"),ge=({clientSecret:t,customerId:e,customerEmail:o,amount:u,currency:l="usd",description:i,metadata:E,onSuccess:m,onError:s,onLoading:I,containerStyle:O,showBillingDetails:g=!0})=>{let{confirmPayment:d}=(0,de.useStripe)(),{initialized:A}=Y(),[r,w]=(0,oe.useState)(!1),[V,F]=(0,oe.useState)(o||""),[K,N]=(0,oe.useState)(""),[P,n]=(0,oe.useState)(""),[p,D]=(0,oe.useState)(!1),T=c=>{s?.(c),x.Alert.alert("Payment Error",c),console.error("Payment error:",c)},f=async()=>{if(!A){T(h.PROVIDER_NOT_CONFIGURED);return}if(g&&V&&!X(V)){T("Please enter a valid email address");return}if(!p){T("Please complete your card information");return}let c=t;if(!c&&u)try{let S=await fetch("/api/payments/create-payment-intent",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({amount:u,currency:l,customerId:e,description:i,metadata:E})});if(!S.ok)throw new Error("Failed to create payment intent");let{client_secret:y}=await S.json();c=y}catch{T("Failed to initialize payment");return}if(!c){T("Payment could not be initialized");return}w(!0),I?.(!0);try{let S=g?{email:V||void 0,name:K||void 0,phone:P||void 0}:void 0,{error:y,paymentIntent:a}=await d(c,{paymentMethodType:"Card",paymentMethodData:{billingDetails:S}});if(y)throw new Error(y.message||h.PAYMENT_FAILED);if(a?.status==="Succeeded")m?.(a),x.Alert.alert("Success","Payment completed successfully!");else throw new Error("Payment was not completed")}catch(S){let y=S instanceof Error?S.message:h.PAYMENT_FAILED;T(y)}finally{w(!1),I?.(!1)}};return(0,L.jsx)(x.KeyboardAvoidingView,{behavior:x.Platform.OS==="ios"?"padding":"height",style:[$.container,O],children:(0,L.jsxs)(x.ScrollView,{showsVerticalScrollIndicator:!1,children:[g&&(0,L.jsxs)(x.View,{style:$.billingSection,children:[(0,L.jsx)(x.Text,{style:$.sectionTitle,children:"Billing Information"}),(0,L.jsxs)(x.View,{style:$.inputContainer,children:[(0,L.jsx)(x.Text,{style:$.inputLabel,children:"Email *"}),(0,L.jsx)(x.TextInput,{style:$.textInput,value:V,onChangeText:F,placeholder:"your@email.com",keyboardType:"email-address",autoCapitalize:"none",autoCorrect:!1})]}),(0,L.jsxs)(x.View,{style:$.inputContainer,children:[(0,L.jsx)(x.Text,{style:$.inputLabel,children:"Full Name"}),(0,L.jsx)(x.TextInput,{style:$.textInput,value:K,onChangeText:N,placeholder:"John Doe",autoCapitalize:"words"})]}),(0,L.jsxs)(x.View,{style:$.inputContainer,children:[(0,L.jsx)(x.Text,{style:$.inputLabel,children:"Phone"}),(0,L.jsx)(x.TextInput,{style:$.textInput,value:P,onChangeText:n,placeholder:"+1 (555) 123-4567",keyboardType:"phone-pad"})]})]}),(0,L.jsxs)(x.View,{style:$.cardSection,children:[(0,L.jsx)(x.Text,{style:$.sectionTitle,children:"Payment Information"}),(0,L.jsx)(x.View,{style:$.cardContainer,children:(0,L.jsx)(de.CardField,{postalCodeEnabled:!0,placeholders:{number:"4242 4242 4242 4242"},cardStyle:Ze,style:$.cardFieldContainer,onCardChange:c=>{D(c.complete)}})})]}),(0,L.jsx)(x.TouchableOpacity,{style:[$.payButton,r&&$.payButtonDisabled],onPress:f,disabled:r||!p,activeOpacity:.8,children:r?(0,L.jsx)(x.ActivityIndicator,{color:"#ffffff",size:"small"}):(0,L.jsxs)(x.Text,{style:$.payButtonText,children:["Pay ",u?`$${(u/100).toFixed(2)}`:""]})})]})})},Ze={backgroundColor:"#fafafa",textColor:"#333",fontSize:16,placeholderColor:"#999"},$=x.StyleSheet.create({container:{flex:1,padding:20,backgroundColor:"#ffffff"},billingSection:{marginBottom:24},cardSection:{marginBottom:32},sectionTitle:{fontSize:18,fontWeight:"600",color:"#333",marginBottom:16},inputContainer:{marginBottom:16},inputLabel:{fontSize:14,fontWeight:"500",color:"#555",marginBottom:8},textInput:{borderWidth:1,borderColor:"#ddd",borderRadius:8,paddingHorizontal:12,paddingVertical:12,fontSize:16,backgroundColor:"#fafafa"},cardContainer:{borderWidth:1,borderColor:"#ddd",borderRadius:8,backgroundColor:"#fafafa"},cardFieldContainer:{width:"100%",height:50},payButton:{backgroundColor:"#007AFF",paddingVertical:16,borderRadius:8,alignItems:"center",justifyContent:"center",minHeight:52},payButtonDisabled:{opacity:.5},payButtonText:{color:"#ffffff",fontSize:18,fontWeight:"600"}});var ve=require("@stripe/stripe-react-native"),ne=require("react-native");var ke=require("react/jsx-runtime"),Ae=({customerId:t,amount:e,currency:o="usd",paymentIntentClientSecret:u,onSuccess:l,onError:i,children:E})=>{let{presentPaymentSheet:m,initPaymentSheet:s}=(0,ve.useStripe)(),{initialized:I}=Y(),O=async()=>{if(!I){i?.("Payment provider not initialized");return}try{if(u){let{error:d}=await s({merchantDisplayName:"Your App Name",paymentIntentClientSecret:u,defaultBillingDetails:{name:""},allowsDelayedPaymentMethods:!0});if(d)throw new Error(d.message)}let{error:g}=await m();if(g){if(g.code==="Canceled")return;throw new Error(g.message)}l?.({status:"succeeded"})}catch(g){let d=g instanceof Error?g.message:"Payment failed";i?.(d),ne.Alert.alert("Payment Error",d)}};return(0,ke.jsx)(ne.View,{style:Qe.container,children:E})},Qe=ne.StyleSheet.create({container:{flex:1}});var pe=require("react"),b=require("react-native");var C=require("react/jsx-runtime"),Ue=({subscription:t,onCancel:e,onReactivate:o,onUpdate:u,style:l})=>{let{activeSubscription:i,loading:E,error:m}=Y(),[s,I]=(0,pe.useState)(null);(0,pe.useEffect)(()=>{I(t||i)},[t,i]);let O=()=>{s&&b.Alert.alert("Cancel Subscription","Are you sure you want to cancel your subscription? You will retain access until the end of your current billing period.",[{text:"Keep Subscription",style:"cancel"},{text:"Cancel",style:"destructive",onPress:()=>e?.(s.id)}])},g=()=>{s&&b.Alert.alert("Reactivate Subscription","Would you like to reactivate your subscription?",[{text:"No",style:"cancel"},{text:"Reactivate",onPress:()=>o?.(s.id)}])},d=V=>{switch(V){case"active":return"#10B981";case"trialing":return"#3B82F6";case"past_due":return"#F59E0B";case"canceled":return"#EF4444";default:return"#6B7280"}},A=V=>{switch(V){case"active":return"Active";case"trialing":return"Trial";case"past_due":return"Past Due";case"canceled":return"Canceled";default:return V}};if(E)return(0,C.jsx)(b.View,{style:[R.container,l],children:(0,C.jsx)(b.Text,{style:R.loadingText,children:"Loading subscription..."})});if(m)return(0,C.jsx)(b.View,{style:[R.container,l],children:(0,C.jsxs)(b.Text,{style:R.errorText,children:["Error: ",m.message]})});if(!s)return(0,C.jsx)(b.View,{style:[R.container,l],children:(0,C.jsx)(b.Text,{style:R.noSubscriptionText,children:"No active subscription"})});let r=s.status==="active"||s.status==="trialing",w=s.status==="canceled";return(0,C.jsxs)(b.ScrollView,{style:[R.container,l],children:[(0,C.jsxs)(b.View,{style:R.header,children:[(0,C.jsx)(b.Text,{style:R.title,children:"Subscription Details"}),(0,C.jsx)(b.View,{style:[R.statusBadge,{backgroundColor:d(s.status)}],children:(0,C.jsx)(b.Text,{style:R.statusText,children:A(s.status)})})]}),(0,C.jsxs)(b.View,{style:R.detailsContainer,children:[(0,C.jsxs)(b.View,{style:R.detailRow,children:[(0,C.jsx)(b.Text,{style:R.detailLabel,children:"Amount:"}),(0,C.jsx)(b.Text,{style:R.detailValue,children:he(s.amount||0,s.currency)})]}),(0,C.jsxs)(b.View,{style:R.detailRow,children:[(0,C.jsx)(b.Text,{style:R.detailLabel,children:"Billing Interval:"}),(0,C.jsx)(b.Text,{style:R.detailValue,children:s.interval})]}),(0,C.jsxs)(b.View,{style:R.detailRow,children:[(0,C.jsx)(b.Text,{style:R.detailLabel,children:"Current Period:"}),(0,C.jsxs)(b.Text,{style:R.detailValue,children:[ce(s.currentPeriodStart)," -"," ",ce(s.currentPeriodEnd)]})]}),s.trialEnd&&(0,C.jsxs)(b.View,{style:R.detailRow,children:[(0,C.jsx)(b.Text,{style:R.detailLabel,children:"Trial Ends:"}),(0,C.jsx)(b.Text,{style:R.detailValue,children:ce(s.trialEnd)})]}),s.cancelAtPeriodEnd&&(0,C.jsx)(b.View,{style:R.warningContainer,children:(0,C.jsxs)(b.Text,{style:R.warningText,children:["Your subscription will cancel on"," ",ce(s.currentPeriodEnd)]})})]}),(0,C.jsxs)(b.View,{style:R.actionsContainer,children:[r&&!s.cancelAtPeriodEnd&&(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(b.TouchableOpacity,{style:R.primaryButton,onPress:()=>u?.(s.id),children:(0,C.jsx)(b.Text,{style:R.primaryButtonText,children:"Update Plan"})}),(0,C.jsx)(b.TouchableOpacity,{style:R.dangerButton,onPress:O,children:(0,C.jsx)(b.Text,{style:R.dangerButtonText,children:"Cancel Subscription"})})]}),s.cancelAtPeriodEnd&&(0,C.jsx)(b.TouchableOpacity,{style:R.primaryButton,onPress:g,children:(0,C.jsx)(b.Text,{style:R.primaryButtonText,children:"Reactivate Subscription"})}),w&&(0,C.jsx)(b.TouchableOpacity,{style:R.primaryButton,onPress:()=>u?.(s.id),children:(0,C.jsx)(b.Text,{style:R.primaryButtonText,children:"Subscribe Again"})})]})]})},R=b.StyleSheet.create({container:{flex:1,backgroundColor:"#FFFFFF",padding:16},header:{flexDirection:"row",justifyContent:"space-between",alignItems:"center",marginBottom:24},title:{fontSize:24,fontWeight:"bold",color:"#1F2937"},statusBadge:{paddingHorizontal:12,paddingVertical:6,borderRadius:16},statusText:{color:"#FFFFFF",fontSize:12,fontWeight:"600"},detailsContainer:{backgroundColor:"#F9FAFB",borderRadius:8,padding:16,marginBottom:24},detailRow:{flexDirection:"row",justifyContent:"space-between",alignItems:"center",paddingVertical:8,borderBottomWidth:1,borderBottomColor:"#E5E7EB"},detailLabel:{fontSize:14,color:"#6B7280",fontWeight:"500"},detailValue:{fontSize:14,color:"#1F2937",fontWeight:"600"},warningContainer:{backgroundColor:"#FEF3C7",borderRadius:8,padding:12,marginTop:16},warningText:{color:"#92400E",fontSize:14,textAlign:"center"},actionsContainer:{gap:12},primaryButton:{backgroundColor:"#3B82F6",borderRadius:8,padding:16,alignItems:"center"},primaryButtonText:{color:"#FFFFFF",fontSize:16,fontWeight:"600"},dangerButton:{backgroundColor:"#EF4444",borderRadius:8,padding:16,alignItems:"center"},dangerButtonText:{color:"#FFFFFF",fontSize:16,fontWeight:"600"},loadingText:{textAlign:"center",color:"#6B7280",fontSize:16},errorText:{textAlign:"center",color:"#EF4444",fontSize:16},noSubscriptionText:{textAlign:"center",color:"#6B7280",fontSize:16}});var be=require("react"),j=require("react-native"),Ve=require("@stripe/stripe-react-native"),H=require("react/jsx-runtime"),Se=null;try{Se=require("react-native-touch-id")}catch{}var Xe={title:"Authentication Required",imageColor:"#e00606",sensorDescription:"Touch sensor",sensorErrorDescription:"Failed",cancelText:"Cancel",fallbackLabel:"Show Passcode",unifiedErrors:!1,passcodeFallback:!1},Me=({amount:t,currency:e="USD",paymentMethodId:o,clientSecret:u,onSuccess:l,onError:i,onCancel:E,title:m="Authorize Payment",subtitle:s,style:I})=>{let[O,g]=(0,be.useState)(!1),[d,A]=(0,be.useState)(!1),{confirmPayment:r}=(0,Ve.useStripe)(),w=async()=>{try{return await Se.isSupported()!==!1}catch{return!1}},V=async()=>{try{return await Se.authenticate("Authenticate to complete your payment",Xe),!0}catch(n){return n.name==="UserCancel"||n.name==="UserFallback"?E?.():i?.(`Authentication failed: ${n.message}`),!1}},F=async()=>{if(!u){i?.("Payment configuration is missing");return}A(!0);try{let{error:n,paymentIntent:p}=await r(u,{paymentMethodType:"Card"});if(n)throw new Error(n.message);l?.(p)}catch(n){let p=n instanceof Error?n.message:"Payment failed";i?.(p)}finally{A(!1)}},K=async()=>{g(!0);try{if(!await w()){j.Alert.alert("Biometric Authentication Not Available","Your device does not support biometric authentication. Please use an alternative payment method.",[{text:"OK",onPress:E}]);return}await V()&&await F()}catch(n){let p=n instanceof Error?n.message:"Authentication failed";i?.(p)}finally{g(!1)}},N=(n,p)=>new Intl.NumberFormat("en-US",{style:"currency",currency:p.toUpperCase()}).format(n/100),P=()=>j.Platform.OS==="ios"?"\u{1F446}":"\u{1F512}";return(0,H.jsx)(j.View,{style:[q.container,I],children:(0,H.jsxs)(j.View,{style:q.content,children:[(0,H.jsx)(j.Text,{style:q.title,children:m}),s&&(0,H.jsx)(j.Text,{style:q.subtitle,children:s}),(0,H.jsxs)(j.View,{style:q.amountContainer,children:[(0,H.jsx)(j.Text,{style:q.amountLabel,children:"Amount"}),(0,H.jsx)(j.Text,{style:q.amount,children:N(t,e)})]}),(0,H.jsxs)(j.TouchableOpacity,{style:[q.payButton,(O||d)&&q.payButtonDisabled],onPress:K,disabled:O||d,children:[(0,H.jsx)(j.Text,{style:q.biometricIcon,children:P()}),(0,H.jsx)(j.Text,{style:q.payButtonText,children:O?"Authenticating...":d?"Processing...":`Pay with ${j.Platform.OS==="ios"?"Touch ID":"Biometrics"}`})]}),(0,H.jsx)(j.Text,{style:q.securityNote,children:"Your payment information is secured with biometric authentication"})]})})},q=j.StyleSheet.create({container:{backgroundColor:"#FFFFFF",borderRadius:12,padding:20,margin:16,shadowColor:"#000",shadowOffset:{width:0,height:2},shadowOpacity:.1,shadowRadius:3.84,elevation:5},content:{alignItems:"center"},title:{fontSize:20,fontWeight:"bold",color:"#1F2937",marginBottom:8,textAlign:"center"},subtitle:{fontSize:14,color:"#6B7280",marginBottom:20,textAlign:"center"},amountContainer:{backgroundColor:"#F9FAFB",borderRadius:8,padding:16,marginBottom:24,minWidth:200,alignItems:"center"},amountLabel:{fontSize:12,color:"#6B7280",marginBottom:4},amount:{fontSize:24,fontWeight:"bold",color:"#1F2937"},payButton:{backgroundColor:"#3B82F6",borderRadius:8,paddingVertical:16,paddingHorizontal:32,flexDirection:"row",alignItems:"center",marginBottom:12},payButtonDisabled:{backgroundColor:"#9CA3AF"},biometricIcon:{fontSize:20,marginRight:8},payButtonText:{color:"#FFFFFF",fontSize:16,fontWeight:"600"},securityNote:{fontSize:12,color:"#6B7280",textAlign:"center",marginTop:8}});var Be=require("@stripe/stripe-react-native");var ee=require("react-native"),te=require("react/jsx-runtime"),Le=({children:t,merchantIdentifier:e,urlScheme:o,publishableKey:u,setReturnUrlSchemeOnAndroid:l=!1})=>{let{config:i,initialized:E}=Y();if(!E)return i?.environment==="development"?(0,te.jsxs)(ee.View,{style:fe.errorContainer,children:[(0,te.jsx)(ee.Text,{style:fe.errorTitle,children:"Payments Provider Error"}),(0,te.jsx)(ee.Text,{style:fe.errorMessage,children:h.PROVIDER_NOT_CONFIGURED}),(0,te.jsx)(ee.Text,{style:fe.errorSubtext,children:"Please check your PaymentsProvider configuration."})]}):null;let m=u||i?.publishableKey;return m?(0,te.jsx)(Be.StripeProvider,{publishableKey:m,merchantIdentifier:e,urlScheme:o,setReturnUrlSchemeOnAndroid:l,children:t}):null},fe=ee.StyleSheet.create({errorContainer:{padding:20,backgroundColor:"#fee",borderColor:"#fcc",borderWidth:1,borderRadius:4,margin:10},errorTitle:{fontWeight:"bold",fontSize:16,color:"#c53030",marginBottom:8},errorMessage:{fontSize:14,color:"#c53030",marginBottom:4},errorSubtext:{fontSize:12,color:"#a0a0a0"}});var G=require("react"),se=require("react-native");var je=(t={})=>{let{customerId:e,subscriptionId:o,autoFetch:u=!0,onError:l,showErrorAlert:i=!0}=t,[E,m]=(0,G.useState)(null),[s,I]=(0,G.useState)([]),[O,g]=(0,G.useState)(!1),[d,A]=(0,G.useState)(null),r=(0,G.useCallback)(n=>{A(n),l?.(n),i&&se.Alert.alert("Subscription Error",n),console.error("Subscription error:",n)},[l,i]),w=(0,G.useCallback)(async n=>{if(!W(n,"subscription"))return r("Invalid subscription ID"),null;try{let p=await fetch(`/api/payments/subscription/${n}`);if(!p.ok){let T=await p.json().catch(()=>({error:"Network error"}));throw new Error(T.error||h.SUBSCRIPTION_NOT_FOUND)}return await p.json()}catch(p){let D=p instanceof Error?p.message:h.SUBSCRIPTION_NOT_FOUND;return r(D),null}},[r]),V=(0,G.useCallback)(async n=>{if(!W(n,"customer"))return r("Invalid customer ID"),[];try{let p=await fetch(`/api/payments/customer/${n}/subscriptions`);if(!p.ok){let T=await p.json().catch(()=>({error:"Network error"}));throw new Error(T.error||h.CUSTOMER_NOT_FOUND)}return(await p.json()).subscriptions||[]}catch(p){let D=p instanceof Error?p.message:h.CUSTOMER_NOT_FOUND;return r(D),[]}},[r]),F=(0,G.useCallback)(async()=>{if(!e&&!o){r("Either customerId or subscriptionId is required");return}g(!0),A(null);try{if(o){let n=await w(o);m(n)}if(e){let n=await V(e);if(I(n),!o&&n.length>0){let p=n.find(D=>D.status==="active")||n[0];m(p)}}}finally{g(!1)}},[e,o,w,V,r]),K=(0,G.useCallback)(async n=>{let p=n||o;return p?W(p,"subscription")?new Promise(D=>{se.Alert.alert("Cancel Subscription","Are you sure you want to cancel your subscription? It will remain active until the end of your current billing period.",[{text:"Keep Subscription",style:"cancel",onPress:()=>D(!1)},{text:"Cancel Subscription",style:"destructive",onPress:async()=>{try{let T=await fetch(`/api/payments/subscription/${p}/cancel`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!T.ok){let f=await T.json().catch(()=>({error:"Network error"}));throw new Error(f.error||"Failed to cancel subscription")}await F(),se.Alert.alert("Success","Your subscription has been cancelled and will end at the end of your current billing period."),D(!0)}catch(T){let f=T instanceof Error?T.message:"Failed to cancel subscription";r(f),D(!1)}}}])}):(r("Invalid subscription ID"),!1):(r("Subscription ID is required to cancel"),!1)},[o,F,r]),N=(0,G.useCallback)(async n=>{let p=n||o;if(!p)return r("Subscription ID is required to reactivate"),!1;if(!W(p,"subscription"))return r("Invalid subscription ID"),!1;try{let D=await fetch(`/api/payments/subscription/${p}/reactivate`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!D.ok){let T=await D.json().catch(()=>({error:"Network error"}));throw new Error(T.error||"Failed to reactivate subscription")}return await F(),se.Alert.alert("Success","Your subscription has been reactivated!"),!0}catch(D){let T=D instanceof Error?D.message:"Failed to reactivate subscription";return r(T),!1}},[o,F,r]),P=(0,G.useCallback)(async(n,p)=>{if(!W(n,"subscription"))return r("Invalid subscription ID"),!1;try{let D=await fetch(`/api/payments/subscription/${n}/payment-method`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({paymentMethodId:p})});if(!D.ok){let T=await D.json().catch(()=>({error:"Network error"}));throw new Error(T.error||"Failed to update payment method")}return await F(),se.Alert.alert("Success","Payment method updated successfully!"),!0}catch(D){let T=D instanceof Error?D.message:"Failed to update payment method";return r(T),!1}},[F,r]);return(0,G.useEffect)(()=>{u&&(e||o)&&F()},[u,e,o,F]),{subscription:E,subscriptions:s,loading:O,error:d,isLoading:O,isError:!!d,refetch:F,cancel:K,reactivate:N,updatePaymentMethod:P}};var Q=require("react"),Ee=require("react-native"),$e=require("@stripe/stripe-react-native");var Ce=(t={})=>{let{onSuccess:e,onError:o,onLoading:u,showErrorAlert:l=!0,showSuccessAlert:i=!0}=t,{initPaymentSheet:E,presentPaymentSheet:m,confirmPayment:s}=(0,$e.useStripe)(),{initialized:I}=Y(),[O,g]=(0,Q.useState)(!1),[d,A]=(0,Q.useState)(null),r=(0,Q.useCallback)(N=>{A(N),o?.(N),l&&Ee.Alert.alert("Payment Error",N),console.error("Checkout error:",N)},[o,l]),w=(0,Q.useCallback)(N=>{e?.(N),i&&Ee.Alert.alert("Success","Payment completed successfully!")},[e,i]),V=(0,Q.useCallback)(async N=>{if(!I)return r(h.PROVIDER_NOT_CONFIGURED),!1;if(!W(N.priceId,"price"))return r(h.INVALID_PRICE_ID),!1;if(N.customerId&&!W(N.customerId,"customer"))return r(h.INVALID_CUSTOMER_ID),!1;if(N.customerEmail&&!X(N.customerEmail))return r("Invalid customer email"),!1;g(!0),A(null),u?.(!0);try{let P=await fetch("/api/payments/create-subscription-setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(N)});if(!P.ok){let c=await P.json().catch(()=>({error:"Network error"}));throw new Error(c.error||"Failed to create subscription setup")}let{setupIntentClientSecret:n,customerId:p,customerEphemeralKeySecret:D}=await P.json();if(!n)throw new Error("No setup intent client secret returned from server");let{error:T}=await E({setupIntentClientSecret:n,customerId:p,customerEphemeralKeySecret:D,merchantDisplayName:"Your App Name",allowsDelayedPaymentMethods:!0});if(T)throw new Error(T.message||"Failed to initialize payment sheet");let{error:f}=await m();if(f){if(f.code==="Canceled")return!1;throw new Error(f.message||h.PAYMENT_FAILED)}return w({type:"subscription",customerId:p}),!0}catch(P){let n=P instanceof Error?P.message:"Failed to create subscription";return r(n),!1}finally{g(!1),u?.(!1)}},[I,E,m,r,w,u]),F=(0,Q.useCallback)(async N=>{if(!I)return r(h.PROVIDER_NOT_CONFIGURED),null;if(N.amount<=0)return r("Amount must be greater than 0"),null;if(N.customerId&&!W(N.customerId,"customer"))return r(h.INVALID_CUSTOMER_ID),null;g(!0),A(null),u?.(!0);try{let P=await fetch("/api/payments/create-payment-intent",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(N)});if(!P.ok){let p=await P.json().catch(()=>({error:"Network error"}));throw new Error(p.error||"Failed to create payment intent")}let{client_secret:n}=await P.json();if(!n)throw new Error("No client secret returned from server");return n}catch(P){let n=P instanceof Error?P.message:"Failed to create payment intent";return r(n),null}finally{g(!1),u?.(!1)}},[I,r,u]),K=(0,Q.useCallback)(async(N,P)=>{if(!I)return r(h.PROVIDER_NOT_CONFIGURED),!1;if(P?.email&&!X(P.email))return r("Invalid email address"),!1;g(!0),A(null),u?.(!0);try{let{error:n,paymentIntent:p}=await s(N,{paymentMethodType:"Card",paymentMethodData:{billingDetails:P}});if(n)throw new Error(n.message||h.PAYMENT_FAILED);if(p?.status==="Succeeded")return w({type:"payment",paymentIntent:p}),!0;throw new Error("Payment was not completed")}catch(n){let p=n instanceof Error?n.message:h.PAYMENT_FAILED;return r(p),!1}finally{g(!1),u?.(!1)}},[I,s,r,w,u]);return{loading:O,error:d,isLoading:O,isError:!!d,createSubscription:V,createPaymentIntent:F,processPayment:K}};var z=require("react"),ue=require("react-native");var ze=(t={})=>{let{customerId:e,autoFetch:o=!0,onError:u,showErrorAlert:l=!0,showSuccessAlert:i=!0}=t,[E,m]=(0,z.useState)(null),[s,I]=(0,z.useState)([]),[O,g]=(0,z.useState)(!1),[d,A]=(0,z.useState)(null),r=(0,z.useCallback)(f=>{A(f),u?.(f),l&&ue.Alert.alert("Customer Error",f),console.error("Customer error:",f)},[u,l]),w=(0,z.useCallback)(f=>{i&&ue.Alert.alert("Success",f)},[i]),V=(0,z.useCallback)(async f=>{if(!W(f,"customer"))return r("Invalid customer ID"),null;try{let c=await fetch(`/api/payments/customer/${f}`);if(!c.ok){let y=await c.json().catch(()=>({error:"Network error"}));throw new Error(y.error||h.CUSTOMER_NOT_FOUND)}return await c.json()}catch(c){let S=c instanceof Error?c.message:h.CUSTOMER_NOT_FOUND;return r(S),null}},[r]),F=(0,z.useCallback)(async()=>{if(!e){r("Customer ID is required");return}g(!0),A(null);try{let f=await V(e);m(f)}finally{g(!1)}},[e,V,r]),K=(0,z.useCallback)(async f=>{if(!X(f.email))return r("Invalid email address"),null;g(!0),A(null);try{let c=await fetch("/api/payments/customer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f)});if(!c.ok){let y=await c.json().catch(()=>({error:"Network error"}));throw new Error(y.error||"Failed to create customer")}let S=await c.json();return m(S),w("Customer created successfully!"),S}catch(c){let S=c instanceof Error?c.message:"Failed to create customer";return r(S),null}finally{g(!1)}},[r,w]),N=(0,z.useCallback)(async f=>{if(!e)return r("Customer ID is required"),!1;if(f.email&&!X(f.email))return r("Invalid email address"),!1;g(!0),A(null);try{let c=await fetch(`/api/payments/customer/${e}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(f)});if(!c.ok){let S=await c.json().catch(()=>({error:"Network error"}));throw new Error(S.error||"Failed to update customer")}return await F(),w("Customer updated successfully!"),!0}catch(c){let S=c instanceof Error?c.message:"Failed to update customer";return r(S),!1}finally{g(!1)}},[e,F,r,w]),P=(0,z.useCallback)(async()=>e?new Promise(f=>{ue.Alert.alert("Delete Customer","Are you sure you want to delete this customer? This action cannot be undone.",[{text:"Cancel",style:"cancel",onPress:()=>f(!1)},{text:"Delete",style:"destructive",onPress:async()=>{g(!0),A(null);try{let c=await fetch(`/api/payments/customer/${e}`,{method:"DELETE"});if(!c.ok){let S=await c.json().catch(()=>({error:"Network error"}));throw new Error(S.error||"Failed to delete customer")}m(null),I([]),w("Customer deleted successfully!"),f(!0)}catch(c){let S=c instanceof Error?c.message:"Failed to delete customer";r(S),f(!1)}finally{g(!1)}}}])}):(r("Customer ID is required"),!1),[e,r,w]),n=(0,z.useCallback)(async()=>{if(!e)return r("Customer ID is required"),[];try{let f=await fetch(`/api/payments/customer/${e}/payment-methods`);if(!f.ok){let y=await f.json().catch(()=>({error:"Network error"}));throw new Error(y.error||"Failed to fetch payment methods")}let S=(await f.json()).paymentMethods||[];return I(S),S}catch(f){let c=f instanceof Error?f.message:"Failed to fetch payment methods";return r(c),[]}},[e,r]),p=(0,z.useCallback)(async f=>{if(!e)return r("Customer ID is required"),!1;try{let c=await fetch(`/api/payments/customer/${e}/payment-methods`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paymentMethodId:f})});if(!c.ok){let S=await c.json().catch(()=>({error:"Network error"}));throw new Error(S.error||"Failed to add payment method")}return await n(),w("Payment method added successfully!"),!0}catch(c){let S=c instanceof Error?c.message:"Failed to add payment method";return r(S),!1}},[e,n,r,w]),D=(0,z.useCallback)(async f=>e?new Promise(c=>{ue.Alert.alert("Remove Payment Method","Are you sure you want to remove this payment method?",[{text:"Cancel",style:"cancel",onPress:()=>c(!1)},{text:"Remove",style:"destructive",onPress:async()=>{try{let S=await fetch(`/api/payments/customer/${e}/payment-methods/${f}`,{method:"DELETE"});if(!S.ok){let y=await S.json().catch(()=>({error:"Network error"}));throw new Error(y.error||"Failed to remove payment method")}await n(),w("Payment method removed successfully!"),c(!0)}catch(S){let y=S instanceof Error?S.message:"Failed to remove payment method";r(y),c(!1)}}}])}):(r("Customer ID is required"),!1),[e,n,r,w]),T=(0,z.useCallback)(async f=>{if(!e)return r("Customer ID is required"),!1;try{let c=await fetch(`/api/payments/customer/${e}/default-payment-method`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({paymentMethodId:f})});if(!c.ok){let S=await c.json().catch(()=>({error:"Network error"}));throw new Error(S.error||"Failed to set default payment method")}return await Promise.all([F(),n()]),w("Default payment method updated successfully!"),!0}catch(c){let S=c instanceof Error?c.message:"Failed to set default payment method";return r(S),!1}},[e,F,n,r,w]);return(0,z.useEffect)(()=>{o&&e&&(F(),n())},[o,e,F,n]),{customer:E,paymentMethods:s,loading:O,error:d,isLoading:O,isError:!!d,refetch:F,createCustomer:K,updateCustomer:N,deleteCustomer:P,fetchPaymentMethods:n,addPaymentMethod:p,removePaymentMethod:D,setDefaultPaymentMethod:T}};var et=async t=>{try{let e=await fetch("/api/payments/create-subscription-setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!e.ok)return{error:(await e.json().catch(()=>({error:"Network error"}))).error||"Failed to create subscription setup"};let o=await e.json();return{setupIntentClientSecret:o.setupIntentClientSecret,customerId:o.customerId,customerEphemeralKeySecret:o.customerEphemeralKeySecret}}catch(e){return{error:e instanceof Error?e.message:"Failed to create subscription setup"}}},tt=async t=>{try{let e=await fetch("/api/payments/create-payment-intent",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});return e.ok?{clientSecret:(await e.json()).client_secret}:{error:(await e.json().catch(()=>({error:"Network error"}))).error||"Failed to create payment intent"}}catch(e){return{error:e instanceof Error?e.message:"Failed to create payment intent"}}},rt=t=>{let e=[];return t.publishableKey||e.push("publishableKey is required"),t.provider||e.push("provider is required"),t.provider!=="stripe"&&e.push("Only stripe provider is currently supported"),t.environment||e.push("environment is required"),t.environment&&!["development","production"].includes(t.environment)&&e.push('environment must be either "development" or "production"'),t.publishableKey&&!t.publishableKey.startsWith("pk_")&&e.push('publishableKey must start with "pk_"'),{isValid:e.length===0,errors:e}},ot=t=>{if(typeof t=="string")return t;if(typeof t=="object"&&t!==null){if("message"in t&&typeof t.message=="string")return t.message;if("code"in t&&typeof t.code=="string"){let e=t.code;return{Canceled:"Payment was cancelled",Failed:"Payment failed",card_declined:"Your card was declined.",expired_card:"Your card has expired.",incorrect_cvc:"Your card's security code is incorrect.",processing_error:"An error occurred while processing your card.",incorrect_number:"Your card number is incorrect."}[e]||`Payment failed: ${e}`}}return"An unexpected error occurred."},nt=async t=>{try{let e=await fetch("/api/payments/customer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});return e.ok?{customer:await e.json()}:{error:(await e.json().catch(()=>({error:"Network error"}))).error||"Failed to create customer"}}catch(e){return{error:e instanceof Error?e.message:"Failed to create customer"}}},st=async t=>{try{let e=await fetch(`/api/payments/subscription/${t}`);return e.ok?{subscription:await e.json()}:{error:(await e.json().catch(()=>({error:"Network error"}))).error||h.SUBSCRIPTION_NOT_FOUND}}catch(e){return{error:e instanceof Error?e.message:h.SUBSCRIPTION_NOT_FOUND}}},it=async t=>{try{let e=await fetch(`/api/payments/customer/${t}/subscriptions`);return e.ok?{subscriptions:(await e.json()).subscriptions||[]}:{error:(await e.json().catch(()=>({error:"Network error"}))).error||h.CUSTOMER_NOT_FOUND}}catch(e){return{error:e instanceof Error?e.message:h.CUSTOMER_NOT_FOUND}}},at=async t=>{try{let e=await fetch(`/api/payments/subscription/${t}/cancel`,{method:"POST",headers:{"Content-Type":"application/json"}});return e.ok?{success:!0}:{success:!1,error:(await e.json().catch(()=>({error:"Network error"}))).error||"Failed to cancel subscription"}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Failed to cancel subscription"}}};0&&(module.exports={CheckoutButton,CheckoutForm,MobilePaymentSheet,NativeSubscriptionView,PaymentForm,PaymentsProvider,PricingTable,StripeProvider,TouchIDPayment,cancelSubscription,createCustomer,createPaymentIntent,createSubscriptionSetup,fetchCustomerSubscriptions,fetchSubscription,formatStripeError,useCheckout,useCustomer,usePayments,usePaymentsContext,useStripe,useSubscription,validatePaymentsConfig});
|
|
3
3
|
//# sourceMappingURL=native.js.map
|