@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.
package/README.md ADDED
@@ -0,0 +1,190 @@
1
+ # @flopay/js
2
+
3
+ Browser-side FloPay SDK. Provides `loadFloPay()` to initialize the SDK, a `FloPay` class for managing payment elements and confirmations, `PaymentAPI` for billing API calls, and `createCheckoutSession` for server-initiated checkout flows.
4
+
5
+ Currently backed by Stripe via the `StripeAdapter`. The adapter pattern (`PaymentProviderAdapter` interface) allows swapping providers without changing consumer code.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ pnpm add @flopay/js @stripe/stripe-js
11
+ ```
12
+
13
+ `@stripe/stripe-js` is an optional peer dependency (required when using the Stripe adapter, which is currently the only adapter).
14
+
15
+ ## Quick Start
16
+
17
+ ### Initialize the SDK
18
+
19
+ ```ts
20
+ import { loadFloPay } from '@flopay/js';
21
+
22
+ const flopay = await loadFloPay('pk_test_...', {
23
+ billingApiUrl: 'https://billing.example.com', // optional, enables retrieveSession/retrieveUnifiedSession
24
+ });
25
+ ```
26
+
27
+ `loadFloPay` caches the instance -- calling it again with the same key returns the cached `FloPay` instance. The optional second argument accepts a `FloPayConfig` with `billingApiUrl`, `locale`, and `appearance`.
28
+
29
+ ### Create and Mount Elements
30
+
31
+ ```ts
32
+ const elements = flopay.elements({
33
+ amount: 2999, // in cents
34
+ currency: 'usd',
35
+ });
36
+
37
+ const cardElement = await elements.create('card');
38
+ cardElement.mount(document.getElementById('card-container')!);
39
+ ```
40
+
41
+ ### Tokenize and Confirm Payment
42
+
43
+ ```ts
44
+ // 1. Validate elements
45
+ const { error: submitError } = await flopay.submitElements();
46
+ if (submitError) throw submitError;
47
+
48
+ // 2. Tokenize card into a PaymentMethod
49
+ const { paymentMethodId, error } = await flopay.createPaymentMethod();
50
+ if (error || !paymentMethodId) throw error;
51
+
52
+ // 3. Confirm card payment with a client secret from your server
53
+ const result = await flopay.confirmCardPayment({
54
+ clientSecret: 'pi_xxx_secret_yyy',
55
+ paymentMethodId,
56
+ });
57
+
58
+ if (result.error) {
59
+ console.error(result.error.message);
60
+ } else {
61
+ console.log('Payment status:', result.status);
62
+ }
63
+ ```
64
+
65
+ ### PayPal Payment
66
+
67
+ ```ts
68
+ const result = await flopay.confirmPayPalPayment({
69
+ billingApiUrl: 'https://billing.example.com',
70
+ sessionId: 'session_uuid',
71
+ email: 'user@example.com',
72
+ returnUrl: window.location.href,
73
+ });
74
+
75
+ // After redirect return, resume the payment:
76
+ const resumed = await flopay.resumePayPalPayment();
77
+ if (resumed) {
78
+ console.log('PayPal payment status:', resumed.status);
79
+ }
80
+ ```
81
+
82
+ ### Retrieve a Session
83
+
84
+ ```ts
85
+ // Using billingApiUrl from config (set at init time):
86
+ const session = await flopay.retrieveSession('session_uuid');
87
+ console.log(session.amount, session.currency, session.status);
88
+
89
+ // Or pass billingApiUrl explicitly:
90
+ const session2 = await flopay.retrieveSession('session_uuid', 'https://billing.example.com');
91
+
92
+ // For provider-specific data (Stripe clientSecret, publishableKey, etc.):
93
+ const unified = await flopay.retrieveUnifiedSession('session_uuid');
94
+ console.log(unified.data.stripe?.clientSecret);
95
+ ```
96
+
97
+ ### PaymentAPI (Billing API Client)
98
+
99
+ ```ts
100
+ import { PaymentAPI } from '@flopay/js';
101
+
102
+ const api = new PaymentAPI('https://billing.example.com');
103
+
104
+ // Fetch and normalize a checkout session
105
+ const session = await api.getUnifiedCheckoutSession('session_uuid');
106
+ // session.provider === 'stripe' | 'chargebee' | 'recurly'
107
+ // session.data.session contains the normalized CheckoutSession
108
+
109
+ // Create a PaymentIntent
110
+ const intentResponse = await api.createPaymentIntent(
111
+ 'session_uuid',
112
+ 'user@example.com',
113
+ 'pm_xxx',
114
+ );
115
+
116
+ // Process a tokenized payment
117
+ const processResponse = await api.processPayment('user_id', {
118
+ sessionId: 'session_uuid',
119
+ tokenizedData: { id: 'pm_xxx', type: 'card' },
120
+ accountData: { userId: 'user_id', email: 'user@example.com', firstName: 'John', lastName: 'Doe' },
121
+ });
122
+
123
+ // Check for prior payments (saved card UX)
124
+ const payments = await api.getPaymentsByEmail('user@example.com');
125
+ ```
126
+
127
+ ### createCheckoutSession
128
+
129
+ ```ts
130
+ import { createCheckoutSession } from '@flopay/js';
131
+
132
+ const result = await createCheckoutSession({
133
+ billingApiUrl: 'https://billing.example.com',
134
+ checkoutBaseUrl: 'https://checkout.example.com',
135
+ clientId: 'client_123',
136
+ items: [{
137
+ providerItemId: 'prod_abc',
138
+ providerItemName: 'Pro Plan',
139
+ totalAmount: 49.99,
140
+ overrideAmount: 24.99,
141
+ }],
142
+ account: { userId: 'user_1', email: 'user@example.com' },
143
+ successUrl: '/success',
144
+ cancelUrl: '/cancel',
145
+ redirectParams: { email: 'user@example.com', bg: 'courses', mode: 'confirm' },
146
+ });
147
+ // On 201: browser redirects to checkout page
148
+ // On 204: browser redirects to successUrl (payment method on file)
149
+ ```
150
+
151
+ Use `createCheckoutSessionWithRetries` for automatic retry with exponential backoff on timeout errors.
152
+
153
+ ## API Reference
154
+
155
+ ### Exports
156
+
157
+ | Export | Description |
158
+ |--------|-------------|
159
+ | `loadFloPay(publishableKey, options?)` | Initializes the SDK. Returns a `Promise<FloPay>`. Caches by key. |
160
+ | `FloPay` | Main SDK class. Methods: `elements()`, `submitElements()`, `createPaymentMethod()`, `confirmCardPayment()`, `confirmPayment()`, `confirmPayPalPayment()`, `resumePayPalPayment()`, `retrieveSession()`, `retrieveUnifiedSession()`, `getRawProvider()`, `destroy()` |
161
+ | `FloPayElements` | Element group manager. Methods: `create(type, options?)`, `getElement(type)`, `submit()`, `destroy()` |
162
+ | `StripeAdapter` | `PaymentProviderAdapter` implementation for Stripe |
163
+ | `PaymentAPI` | Billing API client. Methods: `getCheckoutSession()`, `getUnifiedCheckoutSession()`, `processPayment()`, `createPaymentIntent()`, `createSetupIntent()`, `getPaymentsByEmail()` |
164
+ | `createCheckoutSession(options)` | Creates a checkout session and redirects. Returns `CheckoutSessionResult`. |
165
+ | `createCheckoutSessionWithRetries(options)` | Same as above with automatic retries (default 3, exponential backoff). |
166
+
167
+ ### FloPay Class Methods
168
+
169
+ | Method | Returns | Description |
170
+ |--------|---------|-------------|
171
+ | `elements(options?)` | `FloPayElements` | Creates a new elements group. Destroys previous group. |
172
+ | `submitElements()` | `Promise<{ error? }>` | Validates all mounted elements |
173
+ | `createPaymentMethod()` | `Promise<CreatePaymentMethodResult>` | Tokenizes card fields into a `pm_xxx` ID. Auto-detects split fields vs unified PaymentElement. |
174
+ | `confirmCardPayment(params)` | `Promise<ConfirmCardPaymentResult>` | Confirms with `clientSecret` + `paymentMethodId`. Handles 3DS. |
175
+ | `confirmPayment(params)` | `Promise<PaymentResult>` | Confirms using mounted elements + `clientSecret` |
176
+ | `confirmPayPalPayment(params)` | `Promise<ConfirmCardPaymentResult>` | Full PayPal flow: create PM -> create intent -> confirm/redirect |
177
+ | `resumePayPalPayment()` | `Promise<ConfirmCardPaymentResult \| null>` | Resumes after PayPal redirect. Returns `null` if no PayPal params in URL. |
178
+ | `retrieveSession(sessionId, billingApiUrl?)` | `Promise<CheckoutSession>` | Retrieves a checkout session by ID via `GET /v1/checkouts/sessions/{id}`. Uses `billingApiUrl` from config or the optional second argument. |
179
+ | `retrieveUnifiedSession(sessionId, billingApiUrl?)` | `Promise<NormalizedCheckoutSession>` | Retrieves and normalizes a checkout session, including provider-specific data (Stripe `clientSecret`/`publishableKey`, etc.). |
180
+ | `getRawProvider()` | `unknown` | Returns the raw underlying provider instance (e.g. Stripe object) |
181
+ | `destroy()` | `void` | Tears down elements and provider |
182
+
183
+ ### Supported Element Types
184
+
185
+ - `payment` -- Unified PaymentElement (cards, wallets, etc.)
186
+ - `card` -- Combined card input (number + expiry + CVC)
187
+ - `cardNumber` -- Card number field (for split card forms)
188
+ - `cardExpiry` -- Card expiry field
189
+ - `cardCvc` -- Card CVC field
190
+ - `address` -- Address input element