@flopay/node 1.20.15 → 2.0.1
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 +25 -87
- package/dist/flopay-node.d.ts +6 -42
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @flopay/node
|
|
2
2
|
|
|
3
|
-
Server-side FloPay SDK for Node.js. Creates checkout sessions through the FloPay billing API
|
|
3
|
+
Server-side FloPay SDK for Node.js. Creates checkout sessions through the FloPay billing API and mints one-click sessions.
|
|
4
4
|
|
|
5
5
|
## Installation
|
|
6
6
|
|
|
@@ -8,7 +8,7 @@ Server-side FloPay SDK for Node.js. Creates checkout sessions through the FloPay
|
|
|
8
8
|
pnpm add @flopay/node
|
|
9
9
|
```
|
|
10
10
|
|
|
11
|
-
|
|
11
|
+
`@flopay/shared` installs automatically as a dependency. Use it only from trusted server code: your merchant credentials must never reach a browser.
|
|
12
12
|
|
|
13
13
|
### Node.js version
|
|
14
14
|
|
|
@@ -20,7 +20,7 @@ Run `@flopay/node` on a Node.js release patched for CVE-2026-111497 ("Node2Shell
|
|
|
20
20
|
|
|
21
21
|
### Initialize
|
|
22
22
|
|
|
23
|
-
Create one client
|
|
23
|
+
Create one client. The positional secret key is still accepted so 1.x calls keep compiling, but 2.0.0 sends it nowhere: the package makes no payment-processor call.
|
|
24
24
|
|
|
25
25
|
```ts
|
|
26
26
|
import { FloPay } from '@flopay/node';
|
|
@@ -28,7 +28,7 @@ import { FloPay } from '@flopay/node';
|
|
|
28
28
|
const flopay = new FloPay('sk_test_...'); // load the real key from your secret store
|
|
29
29
|
```
|
|
30
30
|
|
|
31
|
-
To mint one-click sessions, also pass your merchant credentials: the client uuid and API token FloPay issued for your merchant client. A server
|
|
31
|
+
To mint one-click sessions, also pass your merchant credentials: the client uuid and API token FloPay issued for your merchant client. A server can pass a single options object with only `merchantCredentials`.
|
|
32
32
|
|
|
33
33
|
```ts
|
|
34
34
|
import { FloPay } from '@flopay/node';
|
|
@@ -58,7 +58,7 @@ Keyless confirm and auto creates (`create()` with `checkoutMode` `'confirm'` or
|
|
|
58
58
|
- `{ status: 201, redirectUrl, nonce }`: send the buyer to `redirectUrl`, the hosted checkout page (`checkoutBaseUrl` + `/secure`, with the session id and your `redirectParams`). `nonce` is the session-bound checkout token; forward it as the `x-checkout-session-token` header on every continuation call for the same session.
|
|
59
59
|
- `{ status: 204 }`: the buyer already has a payment method on file and nothing needs to be shown.
|
|
60
60
|
|
|
61
|
-
The session currency is required. Pass `currency` on the session, or on the first item, subscription, or product. `checkoutMode` defaults to `'
|
|
61
|
+
The session currency is required. Pass `currency` on the session, or on the first item, subscription, or product. `checkoutMode` defaults to `'full'` on this method, and `timeoutMs` to 12 seconds.
|
|
62
62
|
|
|
63
63
|
`checkoutMetadata` accepts `Record<string, string> | null` and is sent unchanged: omitting it leaves the request body unchanged, an explicit `null` is preserved, and `{}` stays an empty map. The billing API is the only authority on metadata limits.
|
|
64
64
|
|
|
@@ -96,14 +96,6 @@ Customers can keep saved payment methods of any type, not only cards, and the se
|
|
|
96
96
|
|
|
97
97
|
Deleting a saved method works the same way for every type, with the same `PaymentMethodRemovalError` responses.
|
|
98
98
|
|
|
99
|
-
### Stripe checkout sessions and customers
|
|
100
|
-
|
|
101
|
-
`checkout.sessions.retrieve()`, `expire()`, and `listLineItems()` call Stripe directly and normalize the result. `customers.create()`, `retrieve()`, and `update()` manage Stripe customers and return a normalized `Customer`.
|
|
102
|
-
|
|
103
|
-
### Verify webhooks
|
|
104
|
-
|
|
105
|
-
`webhooks.constructEvent()` verifies the `Stripe-Signature` header against your webhook signing secret and returns a normalized `WebhookEvent` (`id`, `type`, `data`, `created`). Pass the raw, unparsed request body.
|
|
106
|
-
|
|
107
99
|
## Examples
|
|
108
100
|
|
|
109
101
|
A `getSession` route for `FloPayAutomaticPaymentButton`, built on `createOneClick`. The buyer comes from your own login session, never from the request body:
|
|
@@ -158,7 +150,7 @@ function requiredEnv(name: string): string {
|
|
|
158
150
|
return value;
|
|
159
151
|
}
|
|
160
152
|
|
|
161
|
-
const flopay = new FloPay(requiredEnv('
|
|
153
|
+
const flopay = new FloPay(requiredEnv('FLOPAY_SECRET_KEY'));
|
|
162
154
|
|
|
163
155
|
const result = await flopay.checkout.sessions.create({
|
|
164
156
|
billingApiUrl: 'https://billing.example.com',
|
|
@@ -243,78 +235,19 @@ export async function listSavedApplePay(list: AuthenticatedList): Promise<string
|
|
|
243
235
|
}
|
|
244
236
|
```
|
|
245
237
|
|
|
246
|
-
Verify a Stripe webhook in a plain Node.js HTTP server:
|
|
247
|
-
|
|
248
|
-
```ts
|
|
249
|
-
import { createServer } from 'node:http';
|
|
250
|
-
import { FloPay } from '@flopay/node';
|
|
251
|
-
|
|
252
|
-
const flopay = new FloPay(process.env.STRIPE_SECRET_KEY ?? 'sk_test_...');
|
|
253
|
-
const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET ?? 'whsec_...';
|
|
254
|
-
const MAX_BODY_BYTES = 64 * 1024; // Pick a limit that fits your largest expected event.
|
|
255
|
-
|
|
256
|
-
createServer((request, response) => {
|
|
257
|
-
const chunks: Buffer[] = [];
|
|
258
|
-
let received = 0;
|
|
259
|
-
request.on('data', (chunk: Buffer) => {
|
|
260
|
-
received += chunk.length;
|
|
261
|
-
if (received > MAX_BODY_BYTES) {
|
|
262
|
-
response.writeHead(413, { Connection: 'close' }).end('Payload too large');
|
|
263
|
-
request.destroy();
|
|
264
|
-
return;
|
|
265
|
-
}
|
|
266
|
-
chunks.push(chunk);
|
|
267
|
-
});
|
|
268
|
-
request.on('end', () => {
|
|
269
|
-
try {
|
|
270
|
-
const event = flopay.webhooks.constructEvent(
|
|
271
|
-
Buffer.concat(chunks),
|
|
272
|
-
String(request.headers['stripe-signature']),
|
|
273
|
-
webhookSecret,
|
|
274
|
-
);
|
|
275
|
-
console.log(event.type, event.created);
|
|
276
|
-
response.writeHead(200).end();
|
|
277
|
-
} catch {
|
|
278
|
-
response.writeHead(400).end('Invalid signature');
|
|
279
|
-
}
|
|
280
|
-
});
|
|
281
|
-
}).listen(3000);
|
|
282
|
-
```
|
|
283
|
-
|
|
284
|
-
Manage Stripe customers:
|
|
285
|
-
|
|
286
|
-
```ts
|
|
287
|
-
import { FloPay } from '@flopay/node';
|
|
288
|
-
|
|
289
|
-
const flopay = new FloPay(process.env.STRIPE_SECRET_KEY ?? 'sk_test_...');
|
|
290
|
-
|
|
291
|
-
const customer = await flopay.customers.create({
|
|
292
|
-
email: 'user@example.com',
|
|
293
|
-
name: 'Jane Doe',
|
|
294
|
-
metadata: { plan: 'pro' },
|
|
295
|
-
});
|
|
296
|
-
|
|
297
|
-
const updated = await flopay.customers.update(customer.id, { metadata: { plan: 'enterprise' } });
|
|
298
|
-
const session = await flopay.checkout.sessions.retrieve('cs_test_...');
|
|
299
|
-
console.log(updated.email, session.status, session.amount);
|
|
300
|
-
```
|
|
301
|
-
|
|
302
238
|
## Public API
|
|
303
239
|
|
|
304
240
|
### Exports
|
|
305
241
|
|
|
306
242
|
| Export | Description |
|
|
307
243
|
|--------|-------------|
|
|
308
|
-
| `FloPay` | Server-side client: `new FloPay(secretKey, options?)
|
|
244
|
+
| `FloPay` | Server-side client: `new FloPay(secretKey, options?)`, or `new FloPay(options)` with a single options object |
|
|
309
245
|
| `FloPayNodeOptions` | Constructor options |
|
|
310
|
-
| `STRIPE_API_VERSION` | `'2026-04-22.dahlia'`, the default Stripe API version for direct Stripe operations |
|
|
311
246
|
|
|
312
247
|
### FloPayNodeOptions
|
|
313
248
|
|
|
314
249
|
| Option | Type | Description |
|
|
315
250
|
|--------|------|-------------|
|
|
316
|
-
| `apiVersion` | `string?` | Stripe API version override for direct Stripe operations |
|
|
317
|
-
| `stripeSecretKey` | `string?` | Stripe secret key for direct Stripe operations, instead of the constructor key |
|
|
318
251
|
| `merchantCredentials` | `MerchantCredentials?` | `{ clientUuid, apiToken }`. Sent as HTTP Basic credentials on every session create, and required by `checkout.sessions.createOneClick()` |
|
|
319
252
|
|
|
320
253
|
### FloPay methods
|
|
@@ -323,22 +256,29 @@ console.log(updated.email, session.status, session.amount);
|
|
|
323
256
|
|--------|---------|-------------|
|
|
324
257
|
| `checkout.sessions.create(params)` | `Promise<CheckoutSessionResult>` | Creates a session through the billing API (`POST /v1/checkouts/sessions`). Accepts `CreateSessionParams`. |
|
|
325
258
|
| `checkout.sessions.createOneClick(params)` | `Promise<OneClickSession>` | Mints a credentialed `'confirm'` session for a one-click button's `getSession` and resolves with exactly `{ sessionId, nonce }`. Accepts `CreateOneClickSessionParams`; needs `merchantCredentials`. |
|
|
326
|
-
| `checkout.sessions.retrieve(id)` | `Promise<CheckoutSession>` | Retrieves and normalizes a Stripe checkout session |
|
|
327
|
-
| `checkout.sessions.expire(id)` | `Promise<CheckoutSession>` | Expires a Stripe checkout session |
|
|
328
|
-
| `checkout.sessions.listLineItems(id)` | `Promise<LineItem[]>` | Lists a Stripe checkout session's line items |
|
|
329
|
-
| `customers.create(params)` | `Promise<Customer>` | Creates a Stripe customer |
|
|
330
|
-
| `customers.retrieve(id)` | `Promise<Customer>` | Retrieves a Stripe customer |
|
|
331
|
-
| `customers.update(id, params)` | `Promise<Customer>` | Updates a Stripe customer |
|
|
332
|
-
| `webhooks.constructEvent(payload, signature, secret)` | `WebhookEvent` | Verifies and parses a Stripe webhook event |
|
|
333
259
|
|
|
334
|
-
The parameter and result types (`CreateSessionParams`, `CreateOneClickSessionParams`, `CheckoutSessionResult`, `OneClickSession`, `MerchantCredentials
|
|
335
|
-
|
|
336
|
-
The `retrieve()`, `expire()`, `listLineItems()`, `customers.*` and `webhooks.constructEvent()` methods call Stripe: on a client built without a Stripe key they throw a `FloPayError` (`stripe_key_required`) instead.
|
|
260
|
+
The parameter and result types (`CreateSessionParams`, `CreateOneClickSessionParams`, `CheckoutSessionResult`, `OneClickSession`, `MerchantCredentials`) are exported by `@flopay/shared`.
|
|
337
261
|
|
|
338
262
|
`@flopay/node` has no card-setup method: `CreateCardSetupSessionRequest` and `CardSetupFutureUse`, also exported by `@flopay/shared`, type the body your server sends to the authenticated `POST /v1/checkouts/sessions/setup` route with its own billing API client. Its `merchantCredentials` are used only for session creates.
|
|
339
263
|
|
|
340
264
|
Saved payment methods of any type are typed by `@flopay/shared` too: `SavedPaymentMethodDisplay`, `SavedPaymentMethodFamily` (with the deprecated alias `SavedPaymentMethodType`), `ListSavedPaymentMethodsQuery` and its `SavedPaymentMethodListType` filter values, `AdvertisedPaymentMethod`, and the `isSetupCheckoutSession` guard. `@flopay/node` adds no list or delete method for them.
|
|
341
265
|
|
|
266
|
+
### Breaking changes in 2.0.0
|
|
267
|
+
|
|
268
|
+
`@flopay/node` 2.0.0 creates checkout sessions and nothing else: it no longer constructs the Stripe server SDK and has no `stripe` dependency. `checkout.sessions.create` and `checkout.sessions.createOneClick` remain unchanged. `@flopay/js`, `@flopay/react`, `@flopay/vue`, `@flopay/node` and `@flopay/shared` are released together as 2.0.0.
|
|
269
|
+
|
|
270
|
+
- `STRIPE_API_VERSION`: No replacement: the package makes no direct Stripe call.
|
|
271
|
+
- `checkout.sessions.retrieve`: No Flo replacement.
|
|
272
|
+
- `checkout.sessions.expire`: No Flo replacement.
|
|
273
|
+
- `checkout.sessions.listLineItems`: No Flo replacement.
|
|
274
|
+
- `customers` (`create`, `retrieve`, `update`): No Flo replacement.
|
|
275
|
+
- `webhooks` (`constructEvent`): No Flo replacement.
|
|
276
|
+
- `stripeSecretKey`, `apiVersion` options: No replacement: nothing in the package uses them.
|
|
277
|
+
|
|
278
|
+
These methods existed only to call Stripe directly; they are removed with no replacement. Call your processor's own server SDK if you still need them.
|
|
279
|
+
|
|
280
|
+
**Default checkout mode.** `checkout.sessions.create()` with no `checkoutMode` now defaults to `'full'` (it was `'confirm'` in 1.x). An explicit `'confirm'`, `'auto'` or `'full'` is sent unchanged. Merchants who want the old default must set `checkoutMode: 'confirm'` and send merchant credentials from the server (`merchantCredentials`, or `checkout.sessions.createOneClick` for a one-click button).
|
|
281
|
+
|
|
342
282
|
## Errors
|
|
343
283
|
|
|
344
284
|
SDK validation and billing API failures are `FloPayError`s from `@flopay/shared`; branch on `type` and `code`.
|
|
@@ -349,10 +289,8 @@ SDK validation and billing API failures are `FloPayError`s from `@flopay/shared`
|
|
|
349
289
|
| `CaptureMethodUnsupportedForSubscription` | `validation_error` | `captureMethod: 'manual'` was requested for a cart with a subscription. Thrown before any request. |
|
|
350
290
|
| The billing API's `code`, or `http_<status>` | `api_error` | The billing API rejected session creation. The error keeps the billing API's message and code, with the HTTP status in `statusCode`. |
|
|
351
291
|
| `MissingCheckoutSessionToken` | `api_error` | The billing API created a session but returned no `nonce`, which means it is too old for this SDK. |
|
|
352
|
-
| `resource_missing` | `api_error` | `customers.retrieve()` found a deleted customer. |
|
|
353
292
|
| `merchant_auth_required` | `authentication_error` | `checkout.sessions.createOneClick()`: the billing API did not accept the merchant credentials and created a Full checkout instead of a one-click session. |
|
|
354
293
|
| `merchant_credentials_required` | `authentication_error` | `checkout.sessions.createOneClick()` was called on a client without `merchantCredentials`. Thrown before any request. |
|
|
355
294
|
| `client_id_mismatch` | `validation_error` | `checkout.sessions.createOneClick()` got a `clientId` other than `merchantCredentials.clientUuid`. Thrown before any request, with `param: 'clientId'`. |
|
|
356
|
-
| `stripe_key_required` | `authentication_error` | A Stripe-only method was called on a client built without a Stripe key. |
|
|
357
295
|
|
|
358
|
-
Constructing `FloPay` without a secret key, or from an options object
|
|
296
|
+
Constructing `FloPay` without a secret key, or from an options object without `merchantCredentials`, throws an `authentication_error`. A create request that exceeds `timeoutMs` is aborted, and network failures reject with the underlying fetch error rather than a `FloPayError`.
|
package/dist/flopay-node.d.ts
CHANGED
|
@@ -1,24 +1,15 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
export declare const STRIPE_API_VERSION = "2026-04-22.dahlia";
|
|
1
|
+
import type { CheckoutSessionResult, CreateOneClickSessionParams, CreateSessionParams, MerchantCredentials, OneClickSession } from '@flopay/shared';
|
|
3
2
|
/** Options for the FloPay Node SDK constructor. */
|
|
4
3
|
export interface FloPayNodeOptions {
|
|
5
|
-
apiVersion?: string;
|
|
6
|
-
/** Stripe secret key, required when using Stripe-specific operations. */
|
|
7
|
-
stripeSecretKey?: string;
|
|
8
4
|
/** Merchant credentials sent on every session create and required by `createOneClick`. */
|
|
9
5
|
merchantCredentials?: MerchantCredentials;
|
|
10
6
|
}
|
|
11
7
|
/**
|
|
12
8
|
* Server-side FloPay SDK.
|
|
13
9
|
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
* billing API (`POST /v1/checkouts/sessions`). This mirrors the
|
|
18
|
-
* `createCheckoutSession` function from `clicktech-core-ui`.
|
|
19
|
-
*
|
|
20
|
-
* 2. **Stripe direct mode** — When a `stripeSecretKey` is provided, also
|
|
21
|
-
* exposes direct Stripe operations (customers, webhooks).
|
|
10
|
+
* Creates checkout sessions via the FloPay billing API
|
|
11
|
+
* (`POST /v1/checkouts/sessions`) and mints credentialed one-click sessions.
|
|
12
|
+
* It makes no call to a payment processor.
|
|
22
13
|
*
|
|
23
14
|
* @example
|
|
24
15
|
* ```ts
|
|
@@ -40,8 +31,6 @@ export interface FloPayNodeOptions {
|
|
|
40
31
|
* ```
|
|
41
32
|
*/
|
|
42
33
|
export declare class FloPay {
|
|
43
|
-
/** Built when a Stripe key is configured; Stripe-only operations throw without it. */
|
|
44
|
-
private readonly stripe;
|
|
45
34
|
private readonly merchantCredentials;
|
|
46
35
|
readonly checkout: {
|
|
47
36
|
sessions: {
|
|
@@ -49,27 +38,11 @@ export declare class FloPay {
|
|
|
49
38
|
create: (params: CreateSessionParams) => Promise<CheckoutSessionResult>;
|
|
50
39
|
/** Mint a credentialed Confirm session for a browser one-click button. */
|
|
51
40
|
createOneClick: (params: CreateOneClickSessionParams) => Promise<OneClickSession>;
|
|
52
|
-
/** Retrieve a checkout session from Stripe. */
|
|
53
|
-
retrieve: (id: string) => Promise<CheckoutSession>;
|
|
54
|
-
/** Expire a checkout session on Stripe. */
|
|
55
|
-
expire: (id: string) => Promise<CheckoutSession>;
|
|
56
|
-
/** List line items for a Stripe checkout session. */
|
|
57
|
-
listLineItems: (id: string) => Promise<LineItem[]>;
|
|
58
41
|
};
|
|
59
42
|
};
|
|
60
|
-
readonly webhooks: {
|
|
61
|
-
constructEvent: (payload: string | Buffer, signature: string, secret: string) => WebhookEvent;
|
|
62
|
-
};
|
|
63
|
-
readonly customers: {
|
|
64
|
-
create: (params: CreateCustomerParams) => Promise<Customer>;
|
|
65
|
-
retrieve: (id: string) => Promise<Customer>;
|
|
66
|
-
update: (id: string, params: UpdateCustomerParams) => Promise<Customer>;
|
|
67
|
-
};
|
|
68
43
|
/**
|
|
69
|
-
* @param secretKeyOrOptions Either
|
|
70
|
-
*
|
|
71
|
-
* options form may omit the Stripe key: session creates still work, and the
|
|
72
|
-
* Stripe-only operations throw a `FloPayError`.
|
|
44
|
+
* @param secretKeyOrOptions Either a secret key, with optional options, or a single options
|
|
45
|
+
* object. The options form needs `merchantCredentials`.
|
|
73
46
|
*/
|
|
74
47
|
constructor(secretKeyOrOptions: string | FloPayNodeOptions, options?: FloPayNodeOptions);
|
|
75
48
|
/**
|
|
@@ -89,13 +62,4 @@ export declare class FloPay {
|
|
|
89
62
|
private createOneClickSession;
|
|
90
63
|
/** Posts a session create to the billing API and maps its answer. */
|
|
91
64
|
private postSession;
|
|
92
|
-
private requireStripe;
|
|
93
|
-
private normalizeStripeSession;
|
|
94
|
-
private retrieveSession;
|
|
95
|
-
private expireSession;
|
|
96
|
-
private listLineItems;
|
|
97
|
-
private constructWebhookEvent;
|
|
98
|
-
private createCustomer;
|
|
99
|
-
private retrieveCustomer;
|
|
100
|
-
private updateCustomer;
|
|
101
65
|
}
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var w=Object.defineProperty;var K=Object.getOwnPropertyDescriptor;var v=Object.getOwnPropertyNames;var V=Object.prototype.hasOwnProperty;var q=(e,t)=>{for(var r in t)w(e,r,{get:t[r],enumerable:!0})},Y=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of v(t))!V.call(e,o)&&o!==r&&w(e,o,{get:()=>t[o],enumerable:!(s=K(t,o))||s.enumerable});return e};var L=e=>Y(w({},"__esModule",{value:!0}),e);var ee={};q(ee,{FloPay:()=>m});module.exports=L(ee);var n=require("@flopay/shared");function P(e){return typeof e=="string"&&e.trim()?e:void 0}function T(e){if(typeof e=="string")return e.trim()?e:void 0;if(!Array.isArray(e))return;let t=e.filter(r=>typeof r=="string"&&r.trim().length>0);return t.length>0?t.join("; "):void 0}function G(e,t){let r=t?.error,s=P(t?.code)??P(r?.code)??`http_${e}`,o=T(t?.message)??T(r?.message)??`Failed to create checkout session (HTTP ${e}).`;return new n.FloPayError(o,"api_error",{code:s,statusCode:e})}function J(e){for(let t of e){let r=t.charCodeAt(0);if(r<=8||r>=10&&r<=31||r===127)return!0}return!1}function Q(e){if(!e||e.trim()===""||e.length>n.MAX_IDEMPOTENCY_KEY_LENGTH||J(e))return!1;try{return new Headers({[n.IDEMPOTENCY_KEY_HEADER]:e}).get(n.IDEMPOTENCY_KEY_HEADER)===e}catch{return!1}}var W=new Set(["confirm","auto"]),I=!1;function X(){I||(I=!0,console.warn("[@flopay/node] Keyless confirm/auto session creates are deprecated and may be downgraded to a Full checkout. Configure `merchantCredentials` and mint one-click sessions with `checkout.sessions.createOneClick`."))}function f(e){return!!(e?.clientUuid&&e.apiToken)}function Z(e){return`Basic ${Buffer.from(`${e.clientUuid}:${e.apiToken}`).toString("base64")}`}var m=class{constructor(t,r){let s=typeof t=="object"&&t!==null,o=s?t:r;if(!s&&!t)throw new n.FloPayError("A secret key is required to initialize the FloPay server SDK.","authentication_error");if(s&&!f(o?.merchantCredentials))throw new n.FloPayError("Pass `merchantCredentials` to initialize the FloPay server SDK.","authentication_error");this.merchantCredentials=o?.merchantCredentials,this.checkout={sessions:{create:this.createSession.bind(this),createOneClick:this.createOneClickSession.bind(this)}}}async createSession(t){let r=t.checkoutMode??"full";return W.has(r)&&!f(this.merchantCredentials)&&X(),(await this.postSession(t,r)).result}async createOneClickSession(t){let r=this.merchantCredentials;if(!f(r))throw new n.FloPayError("checkout.sessions.createOneClick needs `merchantCredentials` ({ clientUuid, apiToken }) on the FloPay constructor.","authentication_error",{code:"merchant_credentials_required"});if(t.clientId!==r.clientUuid)throw new n.FloPayError("checkout.sessions.createOneClick: `clientId` must match `merchantCredentials.clientUuid`.","validation_error",{code:"client_id_mismatch",param:"clientId"});let{result:s,body:o}=await this.postSession(t,"confirm");if(P(o?.autoProcessingError?.gatewayErrorCode)===n.MERCHANT_AUTH_REQUIRED_CODE)throw new n.FloPayError("The billing API did not accept the merchant credentials and created a Full checkout instead of a one-click session. Check `merchantCredentials`.","authentication_error",{code:n.MERCHANT_AUTH_REQUIRED_CODE,statusCode:s.status});let u=o?.data?.uuid,l="nonce"in s?s.nonce:void 0;if(s.status!==201||!u||!l)throw new n.FloPayError(`checkout.sessions.createOneClick expected a created session (HTTP 201), got HTTP ${s.status}.`,"api_error",{code:`http_${s.status}`,statusCode:s.status});return{sessionId:u,nonce:l}}async postSession(t,r){let{billingApiUrl:s,checkoutBaseUrl:o,items:u=[],subscriptions:l=[],products:A,account:i,successUrl:N,cancelUrl:U,captureMethod:C,couponCodes:F=[],checkoutMetadata:S,tagsData:b,redirectParams:R={},timeoutMs:D=12e3,clientId:B,currency:H,utmMetadata:y,idempotencyKey:E}=t,p=A??(0,n.foldIntoProducts)(u,l);(0,n.assertCaptureMethodEligible)({captureMethod:C,products:p});let k=(0,n.resolveSessionCurrency)(H,u,l,p);if(!k)throw new n.FloPayError("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});let h={clientId:B,checkoutVersion:n.SDK_VERSION,successUrl:N,cancelUrl:U,currency:k,checkoutMode:r,products:p.map(c=>(0,n.buildProductPayload)(c,k)),accountData:{userId:i.userId,firstName:i.firstName??null,lastName:i.lastName??null,email:i.email,country:i.country??null,gender:i.gender??null,city:i.city??null,state:i.state??null,zip:i.zip??null},couponCodes:F};C==="manual"&&(h.captureMethod=C),S!==void 0&&(h.checkoutMetadata=S),b&&(h.tagsData=b),y&&y.length>0&&(h.utmMetadata=y);let $=`${s.replace(/\/+$/,"")}/v1/checkouts/sessions`,_=new AbortController,j=setTimeout(()=>_.abort(),D),d,a,M=this.merchantCredentials;try{let c=await fetch($,{method:"POST",headers:{"Content-Type":"application/json",...f(M)?{Authorization:Z(M)}:{},...Q(E)?{[n.IDEMPOTENCY_KEY_HEADER]:E}:{}},body:JSON.stringify(h),signal:_.signal});d=c.status;try{a=await c.json()}catch{}}finally{clearTimeout(j)}if(d>=400)throw G(d,a);if(d===201){let c=a?.data?.uuid,O=a?.data?.nonce;if(!c)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!O)throw new n.FloPayError("Checkout session created but no `nonce` was returned by the billing API. Upgrade the billing service to TeamFloPay/backend#640 or later.","api_error",{code:"MissingCheckoutSessionToken"});let g=new URL(`${o.replace(/\/+$/,"")}/secure`);g.searchParams.set("id",c);for(let[x,z]of Object.entries(R))g.searchParams.set(x,z);return{result:{status:201,redirectUrl:g.toString(),nonce:O},body:a}}return d===204?{result:{status:204},body:a}:{result:{status:d},body:a}}};0&&(module.exports={FloPay});
|
package/dist/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
export type { FloPayNodeOptions } from './flopay-node.js';
|
|
2
|
-
export { FloPay
|
|
2
|
+
export { FloPay } from './flopay-node.js';
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{assertCaptureMethodEligible as
|
|
1
|
+
import{assertCaptureMethodEligible as v,buildProductPayload as V,FloPayError as i,foldIntoProducts as q,IDEMPOTENCY_KEY_HEADER as g,MAX_IDEMPOTENCY_KEY_LENGTH as Y,MERCHANT_AUTH_REQUIRED_CODE as T,resolveSessionCurrency as L,SDK_VERSION as G}from"@flopay/shared";function w(e){return typeof e=="string"&&e.trim()?e:void 0}function I(e){if(typeof e=="string")return e.trim()?e:void 0;if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string"&&n.trim().length>0);return t.length>0?t.join("; "):void 0}function J(e,t){let n=t?.error,r=w(t?.code)??w(n?.code)??`http_${e}`,s=I(t?.message)??I(n?.message)??`Failed to create checkout session (HTTP ${e}).`;return new i(s,"api_error",{code:r,statusCode:e})}function Q(e){for(let t of e){let n=t.charCodeAt(0);if(n<=8||n>=10&&n<=31||n===127)return!0}return!1}function W(e){if(!e||e.trim()===""||e.length>Y||Q(e))return!1;try{return new Headers({[g]:e}).get(g)===e}catch{return!1}}var X=new Set(["confirm","auto"]),A=!1;function Z(){A||(A=!0,console.warn("[@flopay/node] Keyless confirm/auto session creates are deprecated and may be downgraded to a Full checkout. Configure `merchantCredentials` and mint one-click sessions with `checkout.sessions.createOneClick`."))}function f(e){return!!(e?.clientUuid&&e.apiToken)}function ee(e){return`Basic ${Buffer.from(`${e.clientUuid}:${e.apiToken}`).toString("base64")}`}var P=class{constructor(t,n){let r=typeof t=="object"&&t!==null,s=r?t:n;if(!r&&!t)throw new i("A secret key is required to initialize the FloPay server SDK.","authentication_error");if(r&&!f(s?.merchantCredentials))throw new i("Pass `merchantCredentials` to initialize the FloPay server SDK.","authentication_error");this.merchantCredentials=s?.merchantCredentials,this.checkout={sessions:{create:this.createSession.bind(this),createOneClick:this.createOneClickSession.bind(this)}}}async createSession(t){let n=t.checkoutMode??"full";return X.has(n)&&!f(this.merchantCredentials)&&Z(),(await this.postSession(t,n)).result}async createOneClickSession(t){let n=this.merchantCredentials;if(!f(n))throw new i("checkout.sessions.createOneClick needs `merchantCredentials` ({ clientUuid, apiToken }) on the FloPay constructor.","authentication_error",{code:"merchant_credentials_required"});if(t.clientId!==n.clientUuid)throw new i("checkout.sessions.createOneClick: `clientId` must match `merchantCredentials.clientUuid`.","validation_error",{code:"client_id_mismatch",param:"clientId"});let{result:r,body:s}=await this.postSession(t,"confirm");if(w(s?.autoProcessingError?.gatewayErrorCode)===T)throw new i("The billing API did not accept the merchant credentials and created a Full checkout instead of a one-click session. Check `merchantCredentials`.","authentication_error",{code:T,statusCode:r.status});let u=s?.data?.uuid,l="nonce"in r?r.nonce:void 0;if(r.status!==201||!u||!l)throw new i(`checkout.sessions.createOneClick expected a created session (HTTP 201), got HTTP ${r.status}.`,"api_error",{code:`http_${r.status}`,statusCode:r.status});return{sessionId:u,nonce:l}}async postSession(t,n){let{billingApiUrl:r,checkoutBaseUrl:s,items:u=[],subscriptions:l=[],products:N,account:o,successUrl:U,cancelUrl:F,captureMethod:m,couponCodes:R=[],checkoutMetadata:S,tagsData:b,redirectParams:D={},timeoutMs:B=12e3,clientId:H,currency:$,utmMetadata:C,idempotencyKey:E}=t,y=N??q(u,l);v({captureMethod:m,products:y});let p=L($,u,l,y);if(!p)throw new i("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});let h={clientId:H,checkoutVersion:G,successUrl:U,cancelUrl:F,currency:p,checkoutMode:n,products:y.map(c=>V(c,p)),accountData:{userId:o.userId,firstName:o.firstName??null,lastName:o.lastName??null,email:o.email,country:o.country??null,gender:o.gender??null,city:o.city??null,state:o.state??null,zip:o.zip??null},couponCodes:R};m==="manual"&&(h.captureMethod=m),S!==void 0&&(h.checkoutMetadata=S),b&&(h.tagsData=b),C&&C.length>0&&(h.utmMetadata=C);let j=`${r.replace(/\/+$/,"")}/v1/checkouts/sessions`,_=new AbortController,x=setTimeout(()=>_.abort(),B),d,a,M=this.merchantCredentials;try{let c=await fetch(j,{method:"POST",headers:{"Content-Type":"application/json",...f(M)?{Authorization:ee(M)}:{},...W(E)?{[g]:E}:{}},body:JSON.stringify(h),signal:_.signal});d=c.status;try{a=await c.json()}catch{}}finally{clearTimeout(x)}if(d>=400)throw J(d,a);if(d===201){let c=a?.data?.uuid,O=a?.data?.nonce;if(!c)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!O)throw new i("Checkout session created but no `nonce` was returned by the billing API. Upgrade the billing service to TeamFloPay/backend#640 or later.","api_error",{code:"MissingCheckoutSessionToken"});let k=new URL(`${s.replace(/\/+$/,"")}/secure`);k.searchParams.set("id",c);for(let[z,K]of Object.entries(D))k.searchParams.set(z,K);return{result:{status:201,redirectUrl:k.toString(),nonce:O},body:a}}return d===204?{result:{status:204},body:a}:{result:{status:d},body:a}}};export{P as FloPay};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@flopay/node",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"sideEffects": false,
|
|
6
6
|
"publishConfig": {
|
|
@@ -26,10 +26,10 @@
|
|
|
26
26
|
"dist"
|
|
27
27
|
],
|
|
28
28
|
"dependencies": {
|
|
29
|
-
"@flopay/shared": "
|
|
30
|
-
"stripe": "^22.6.2"
|
|
29
|
+
"@flopay/shared": "2.0.1"
|
|
31
30
|
},
|
|
32
31
|
"devDependencies": {
|
|
32
|
+
"@types/node": "^24.19.2",
|
|
33
33
|
"tsup": "^9.0.0",
|
|
34
34
|
"typescript": "^7.0.2",
|
|
35
35
|
"vitest": "4.1.12"
|