@flopay/js 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,317 @@
1
+ import * as _flopay_shared from '@flopay/shared';
2
+ import { PaymentProviderAdapter, ElementOptions, ElementType, MountedElement, FloPayError, FloPayConfig, CreatePaymentMethodResult, ConfirmCardPaymentParams, ConfirmCardPaymentResult, ConfirmPaymentParams, PaymentResult, CheckoutSession, NormalizedCheckoutSession, BillingProvider, ProcessPaymentParams, CreateSessionParams, CheckoutSessionResult } from '@flopay/shared';
3
+
4
+ /**
5
+ * Manages the creation and lifecycle of payment elements.
6
+ *
7
+ * Each `FloPayElements` instance is bound to a single provider adapter
8
+ * and tracks all created elements for cleanup.
9
+ */
10
+ declare class FloPayElements {
11
+ private readonly provider;
12
+ private readonly elementMap;
13
+ private readonly baseOptions;
14
+ constructor(provider: PaymentProviderAdapter, options?: ElementOptions);
15
+ /**
16
+ * Creates a new element of the given type.
17
+ * If an element of that type already exists, it is destroyed first.
18
+ */
19
+ create(type: ElementType, options?: ElementOptions): Promise<MountedElement>;
20
+ /** Returns a previously created element, or `null`. */
21
+ getElement(type: ElementType): MountedElement | null;
22
+ /**
23
+ * Submits all mounted elements for validation.
24
+ *
25
+ * Returns an object with an optional error if validation fails.
26
+ * This does NOT confirm the payment — call `floPay.confirmPayment()` for that.
27
+ */
28
+ submit(): Promise<{
29
+ error?: FloPayError;
30
+ }>;
31
+ /** Destroys all created elements and clears the internal map. */
32
+ destroy(): void;
33
+ }
34
+
35
+ /**
36
+ * The main FloPay SDK instance.
37
+ *
38
+ * Created via `loadFloPay(publishableKey)`. Provides element management,
39
+ * payment confirmation, and session retrieval.
40
+ */
41
+ declare class FloPay {
42
+ private readonly provider;
43
+ private readonly config;
44
+ private currentElements;
45
+ constructor(provider: PaymentProviderAdapter, config: FloPayConfig);
46
+ /**
47
+ * Creates a new `FloPayElements` group for mounting payment fields.
48
+ *
49
+ * Only one elements group is active at a time. Creating a new one
50
+ * destroys the previous group.
51
+ */
52
+ elements(options?: ElementOptions): FloPayElements;
53
+ /** Submit elements for validation. */
54
+ submitElements(): Promise<{
55
+ error?: _flopay_shared.FloPayError;
56
+ }>;
57
+ /** Create a payment method from the current elements (tokenize card). */
58
+ createPaymentMethod(): Promise<CreatePaymentMethodResult>;
59
+ /** Confirm a card payment with a known client secret and payment method ID. */
60
+ confirmCardPayment(params: ConfirmCardPaymentParams): Promise<ConfirmCardPaymentResult>;
61
+ /** Confirm a PayPal payment: create intent via billing API → confirm → redirect if needed. */
62
+ confirmPayPalPayment(params: {
63
+ billingApiUrl: string;
64
+ sessionId: string;
65
+ email: string;
66
+ returnUrl: string;
67
+ }): Promise<ConfirmCardPaymentResult>;
68
+ /** Resume a PayPal payment after redirect return. Returns null if no PayPal params in URL. */
69
+ resumePayPalPayment(): Promise<ConfirmCardPaymentResult | null>;
70
+ /** Confirms a payment using the mounted elements. */
71
+ confirmPayment(params: ConfirmPaymentParams): Promise<PaymentResult>;
72
+ /**
73
+ * Retrieves a checkout session by ID via the billing API.
74
+ *
75
+ * Returns the normalized `CheckoutSession` with amount, currency,
76
+ * customer data, and status.
77
+ *
78
+ * Requires `billingApiUrl` to be set — either via `loadFloPay(key, { billingApiUrl })`
79
+ * or passed directly as the second argument.
80
+ */
81
+ retrieveSession(sessionId: string, billingApiUrl?: string): Promise<CheckoutSession>;
82
+ /**
83
+ * Retrieves and normalizes a checkout session, including provider-specific
84
+ * data (Stripe clientSecret/publishableKey, Chargebee site, etc.).
85
+ *
86
+ * The billing API URL is resolved from: explicit param → `loadFloPay()` config
87
+ * → `NEXT_PUBLIC_FLOPAY_ENV` env var → `configureFlopay()` → staging fallback.
88
+ */
89
+ retrieveUnifiedSession(sessionId: string, billingApiUrl?: string): Promise<NormalizedCheckoutSession>;
90
+ /**
91
+ * Returns the raw underlying provider instance (e.g. Stripe object).
92
+ * Used internally by components that need direct provider access,
93
+ * such as PayPal which requires its own Elements instance.
94
+ */
95
+ getRawProvider(): unknown;
96
+ /** Tears down the SDK instance and releases resources. */
97
+ destroy(): void;
98
+ }
99
+
100
+ /**
101
+ * Loads and initializes the FloPay SDK.
102
+ *
103
+ * This is the primary entry point for consumer applications.
104
+ * It initializes the underlying payment provider (currently Stripe)
105
+ * and returns a ready-to-use `FloPay` instance.
106
+ *
107
+ * @example
108
+ * ```ts
109
+ * import { loadFloPay } from '@flopay/js';
110
+ *
111
+ * const flopay = await loadFloPay('pk_test_...');
112
+ * const elements = flopay.elements();
113
+ * const cardElement = await elements.create('card');
114
+ * cardElement.mount('#card-container');
115
+ * ```
116
+ */
117
+ declare function loadFloPay(publishableKey: string, options?: Omit<FloPayConfig, 'publishableKey'>): Promise<FloPay>;
118
+
119
+ /**
120
+ * Payment provider adapter backed by Stripe.
121
+ *
122
+ * Implements the `PaymentProviderAdapter` interface so that FloPay consumers
123
+ * interact with a stable API regardless of the upstream provider.
124
+ */
125
+ declare class StripeAdapter implements PaymentProviderAdapter {
126
+ readonly name = "stripe";
127
+ private stripe;
128
+ private elements;
129
+ initialize(config: FloPayConfig): Promise<void>;
130
+ /** Lazily creates the Stripe Elements group for the given options. */
131
+ private getElements;
132
+ createElement(type: ElementType, options: ElementOptions): Promise<MountedElement>;
133
+ getElement(type: ElementType): MountedElement | null;
134
+ submitElements(): Promise<{
135
+ error?: FloPayError;
136
+ }>;
137
+ createPaymentMethod(): Promise<CreatePaymentMethodResult>;
138
+ confirmCardPayment(params: ConfirmCardPaymentParams): Promise<ConfirmCardPaymentResult>;
139
+ confirmPayment(params: ConfirmPaymentParams): Promise<PaymentResult>;
140
+ confirmPayPalPayment(params: {
141
+ billingApiUrl: string;
142
+ sessionId: string;
143
+ email: string;
144
+ returnUrl: string;
145
+ }): Promise<ConfirmCardPaymentResult>;
146
+ resumePayPalPayment(): Promise<ConfirmCardPaymentResult | null>;
147
+ getRawProvider(): unknown;
148
+ createPayPalElements(options: ElementOptions): unknown;
149
+ destroy(): void;
150
+ }
151
+
152
+ /** Raw billing API response wrapper. */
153
+ interface BillingResponse<T> {
154
+ data: T;
155
+ }
156
+ /** Raw checkout session from the billing API (includes gateway field). */
157
+ interface RawCheckoutSession {
158
+ uuid: string;
159
+ nonce: string;
160
+ gateway?: BillingProvider;
161
+ status: 'pending' | 'completed';
162
+ successUrl: string;
163
+ cancelUrl: string;
164
+ createdAt?: string;
165
+ checkoutUrl?: string;
166
+ items: Array<{
167
+ uuid: string;
168
+ checkoutSessionId: string;
169
+ providerItemId: string;
170
+ providerItemName: string;
171
+ providerItemDescription?: string | null;
172
+ quantity: number;
173
+ totalAmount: number;
174
+ overrideAmount: number | null;
175
+ currency: string;
176
+ metadata?: Record<string, unknown> | null;
177
+ }>;
178
+ subscriptions: Array<{
179
+ uuid: string;
180
+ checkoutSessionId: string;
181
+ providerPlanId: string;
182
+ providerPlanName: string;
183
+ providerPlanDescription?: string | null;
184
+ quantity: number;
185
+ totalAmount: number;
186
+ overrideAmount: number | null;
187
+ currency: string;
188
+ isUpdate?: boolean;
189
+ metadata?: Record<string, unknown> | null;
190
+ }>;
191
+ coupons?: string[];
192
+ checkoutMode?: 'full' | 'auto' | 'confirm';
193
+ gatewayData: {
194
+ publishableKey?: string | null;
195
+ };
196
+ accountData: {
197
+ userId: string;
198
+ firstName: string;
199
+ lastName: string;
200
+ email: string;
201
+ gender?: string | null;
202
+ city?: string | null;
203
+ state?: string | null;
204
+ country?: string | null;
205
+ zip?: string | null;
206
+ };
207
+ tagsData: {
208
+ googleContainerId?: string | null;
209
+ sessionId?: string | null;
210
+ testEventCode?: string | null;
211
+ };
212
+ }
213
+ /**
214
+ * Client-side payment API service.
215
+ *
216
+ * Mirrors the `PaymentAPI` class from the checkout project's
217
+ * `src/service/api.ts`. All methods call the billing API endpoints
218
+ * that the checkout backend exposes.
219
+ */
220
+ declare class PaymentAPI {
221
+ private readonly baseUrl;
222
+ constructor(billingApiUrl: string);
223
+ /** Fetch a raw checkout session by ID. */
224
+ getCheckoutSession(checkoutSessionId: string): Promise<BillingResponse<RawCheckoutSession>>;
225
+ /**
226
+ * Fetch and normalize a checkout session.
227
+ *
228
+ * Reads the backend's `gateway` field to determine the provider,
229
+ * then wraps the session in a `NormalizedCheckoutSession` for
230
+ * provider-agnostic consumption.
231
+ */
232
+ getUnifiedCheckoutSession(checkoutSessionId: string): Promise<NormalizedCheckoutSession>;
233
+ /**
234
+ * Submit a tokenized payment to the billing backend.
235
+ *
236
+ * The backend will either succeed, return `type: '3ds_required'`
237
+ * (with a `threeDSecureToken`), or return `type: 'paypal_redirect_required'`.
238
+ */
239
+ processPayment(userId: string, data: ProcessPaymentParams): Promise<Response>;
240
+ /**
241
+ * Create a PaymentIntent on the backend.
242
+ *
243
+ * Used by the Stripe flow to create a server-side PaymentIntent
244
+ * with the client's payment method attached.
245
+ */
246
+ createPaymentIntent(sessionId: string, email: string, paymentMethodType: string, options?: {
247
+ signal?: AbortSignal;
248
+ isPaypal?: string;
249
+ }): Promise<Response>;
250
+ /**
251
+ * Create a SetupIntent for saving payment methods.
252
+ */
253
+ createSetupIntent(sessionId: string, email: string, paymentMethodType: 'card' | 'google_pay' | 'apple_pay' | 'paypal_express_checkout', options?: {
254
+ signal?: AbortSignal;
255
+ }): Promise<Response>;
256
+ /**
257
+ * Fetch user's prior payments by email.
258
+ * Used to determine if saved card UX should be shown.
259
+ */
260
+ getPaymentsByEmail(email: string, options?: {
261
+ signal?: AbortSignal;
262
+ page?: number;
263
+ limit?: number;
264
+ }): Promise<{
265
+ data: Array<{
266
+ id: string;
267
+ }>;
268
+ total: number;
269
+ page: number;
270
+ limit: number;
271
+ }>;
272
+ /** Convert raw session to the SDK CheckoutSession shape. */
273
+ private toCheckoutSession;
274
+ }
275
+
276
+ /**
277
+ * Creates a checkout session via the billing API and redirects the user
278
+ * to the hosted checkout page.
279
+ *
280
+ * Mirrors `createCheckoutSession` from `clicktech-core-ui/modules`.
281
+ *
282
+ * - On 201: Redirects to `{checkoutBaseUrl}/secure?id={uuid}&...redirectParams`
283
+ * - On 204: Redirects directly to `successUrl` (payment method already on file)
284
+ * - On other: Returns `{ status }` without redirecting
285
+ *
286
+ * @example
287
+ * ```ts
288
+ * import { createCheckoutSession } from '@flopay/js';
289
+ *
290
+ * await createCheckoutSession({
291
+ * billingApiUrl: 'https://billing.example.com',
292
+ * checkoutBaseUrl: 'https://checkout.example.com',
293
+ * clientId: 'client_123',
294
+ * items: [{
295
+ * providerItemId: 'prod_abc',
296
+ * providerItemName: 'Pro Plan',
297
+ * totalAmount: 49.99,
298
+ * overrideAmount: 24.99,
299
+ * }],
300
+ * account: { userId: 'user_1', email: 'user@example.com' },
301
+ * successUrl: '/success',
302
+ * cancelUrl: '/cancel',
303
+ * redirectParams: { email: 'user@example.com', bg: 'courses', mode: 'confirm' },
304
+ * });
305
+ * ```
306
+ */
307
+ declare function createCheckoutSession(options: CreateSessionParams): Promise<CheckoutSessionResult>;
308
+ /**
309
+ * Creates a checkout session with automatic retry on timeout/abort errors.
310
+ *
311
+ * Uses exponential backoff: 100ms, 200ms, 400ms, etc.
312
+ */
313
+ declare function createCheckoutSessionWithRetries(options: CreateSessionParams & {
314
+ maxRetries?: number;
315
+ }): Promise<CheckoutSessionResult>;
316
+
317
+ export { FloPay, FloPayElements, PaymentAPI, StripeAdapter, createCheckoutSession, createCheckoutSessionWithRetries, loadFloPay };