@flopay/node 1.20.14 → 2.0.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 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, retrieves and expires Stripe checkout sessions, manages Stripe customers, and verifies Stripe webhooks.
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
- `stripe` and `@flopay/shared` install automatically as dependencies. Use it only from trusted server code: the constructor takes a Stripe secret key, which must never reach a browser.
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 with your Stripe secret key. Direct Stripe operations use the API version in `STRIPE_API_VERSION` unless you pass `apiVersion`; pass `stripeSecretKey` to use a different key for them.
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 that only creates sessions can pass a single options object with no Stripe key; the Stripe-only methods then throw a `FloPayError`.
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 `'confirm'` on this method, and `timeoutMs` to 12 seconds.
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('STRIPE_SECRET_KEY'));
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?)` with a Stripe secret key (`sk_test_...` or `sk_live_...`), or `new FloPay(options)` with a single options object |
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`, `CheckoutSession`, `Customer`, `LineItem`, `WebhookEvent`) are exported by `@flopay/shared`.
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 with neither `merchantCredentials` nor `stripeSecretKey`, 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`. Stripe operations, including webhook signature verification, reject with Stripe's own errors. Treat a failed `constructEvent()` as an untrusted request.
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`.
@@ -1,24 +1,15 @@
1
- import type { CheckoutSession, CheckoutSessionResult, CreateCustomerParams, CreateOneClickSessionParams, CreateSessionParams, Customer, LineItem, MerchantCredentials, OneClickSession, UpdateCustomerParams, WebhookEvent } from '@flopay/shared';
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
- * Supports two modes of operation:
15
- *
16
- * 1. **Billing API mode** — Creates checkout sessions via the FloPay/ClickTech
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 the secret key (the Stripe key unless
70
- * `options.stripeSecretKey` overrides it), or a single options object. The
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 j=Object.create;var h=Object.defineProperty;var z=Object.getOwnPropertyDescriptor;var W=Object.getOwnPropertyNames;var Y=Object.getPrototypeOf,G=Object.prototype.hasOwnProperty;var J=(r,e)=>{for(var t in e)h(r,t,{get:e[t],enumerable:!0})},M=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of W(e))!G.call(r,i)&&i!==t&&h(r,i,{get:()=>e[i],enumerable:!(n=z(e,i))||n.enumerable});return r};var Q=(r,e,t)=>(t=r!=null?j(Y(r)):{},M(e||!r||!r.__esModule?h(t,"default",{value:r,enumerable:!0}):t,r)),X=r=>M(h({},"__esModule",{value:!0}),r);var oe={};J(oe,{FloPay:()=>C,STRIPE_API_VERSION:()=>w});module.exports=X(oe);var s=require("@flopay/shared"),R=Q(require("stripe"),1),w="2026-04-22.dahlia";function P(r){return typeof r=="string"&&r.trim()?r:void 0}function O(r){if(typeof r=="string")return r.trim()?r:void 0;if(!Array.isArray(r))return;let e=r.filter(t=>typeof t=="string"&&t.trim().length>0);return e.length>0?e.join("; "):void 0}function Z(r,e){let t=e?.error,n=P(e?.code)??P(t?.code)??`http_${r}`,i=O(e?.message)??O(t?.message)??`Failed to create checkout session (HTTP ${r}).`;return new s.FloPayError(i,"api_error",{code:n,statusCode:r})}function ee(r){for(let e of r){let t=e.charCodeAt(0);if(t<=8||t>=10&&t<=31||t===127)return!0}return!1}function te(r){if(!r||r.trim()===""||r.length>s.MAX_IDEMPOTENCY_KEY_LENGTH||ee(r))return!1;try{return new Headers({[s.IDEMPOTENCY_KEY_HEADER]:r}).get(s.IDEMPOTENCY_KEY_HEADER)===r}catch{return!1}}var re=new Set(["confirm","auto"]),T=!1;function se(){T||(T=!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 p(r){return!!(r?.clientUuid&&r.apiToken)}function ne(r){return`Basic ${Buffer.from(`${r.clientUuid}:${r.apiToken}`).toString("base64")}`}function ie(){return new s.FloPayError("This operation needs a Stripe secret key. Pass one as the first constructor argument or as `stripeSecretKey`.","authentication_error",{code:"stripe_key_required"})}var C=class{constructor(e,t){let n=typeof e=="object"&&e!==null,i=n?e:t,a=n?void 0:e;if(!n&&!a)throw new s.FloPayError("A secret key is required to initialize the FloPay server SDK.","authentication_error");if(n&&!i?.stripeSecretKey&&!p(i?.merchantCredentials))throw new s.FloPayError("Pass `merchantCredentials`, `stripeSecretKey` or both to initialize the FloPay server SDK.","authentication_error");this.merchantCredentials=i?.merchantCredentials;let c=i?.stripeSecretKey??a;this.stripe=c?new R.default(c,{apiVersion:i?.apiVersion??w,appInfo:{name:"flopay-node",version:s.SDK_VERSION}}):void 0,this.checkout={sessions:{create:this.createSession.bind(this),createOneClick:this.createOneClickSession.bind(this),retrieve:this.retrieveSession.bind(this),expire:this.expireSession.bind(this),listLineItems:this.listLineItems.bind(this)}},this.webhooks={constructEvent:this.constructWebhookEvent.bind(this)},this.customers={create:this.createCustomer.bind(this),retrieve:this.retrieveCustomer.bind(this),update:this.updateCustomer.bind(this)}}async createSession(e){let t=e.checkoutMode??"confirm";return re.has(t)&&!p(this.merchantCredentials)&&se(),(await this.postSession(e,t)).result}async createOneClickSession(e){let t=this.merchantCredentials;if(!p(t))throw new s.FloPayError("checkout.sessions.createOneClick needs `merchantCredentials` ({ clientUuid, apiToken }) on the FloPay constructor.","authentication_error",{code:"merchant_credentials_required"});if(e.clientId!==t.clientUuid)throw new s.FloPayError("checkout.sessions.createOneClick: `clientId` must match `merchantCredentials.clientUuid`.","validation_error",{code:"client_id_mismatch",param:"clientId"});let{result:n,body:i}=await this.postSession(e,"confirm");if(P(i?.autoProcessingError?.gatewayErrorCode)===s.MERCHANT_AUTH_REQUIRED_CODE)throw new s.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:s.MERCHANT_AUTH_REQUIRED_CODE,statusCode:n.status});let a=i?.data?.uuid,c="nonce"in n?n.nonce:void 0;if(n.status!==201||!a||!c)throw new s.FloPayError(`checkout.sessions.createOneClick expected a created session (HTTP 201), got HTTP ${n.status}.`,"api_error",{code:`http_${n.status}`,statusCode:n.status});return{sessionId:a,nonce:c}}async postSession(e,t){let{billingApiUrl:n,checkoutBaseUrl:i,items:a=[],subscriptions:c=[],products:A,account:o,successUrl:U,cancelUrl:q,captureMethod:f,couponCodes:F=[],checkoutMetadata:b,tagsData:E,redirectParams:x={},timeoutMs:K=12e3,clientId:B,currency:D,utmMetadata:y,idempotencyKey:_}=e,S=A??(0,s.foldIntoProducts)(a,c);(0,s.assertCaptureMethodEligible)({captureMethod:f,products:S});let k=(0,s.resolveSessionCurrency)(D,a,c,S);if(!k)throw new s.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 m={clientId:B,checkoutVersion:s.SDK_VERSION,successUrl:U,cancelUrl:q,currency:k,checkoutMode:t,products:S.map(d=>(0,s.buildProductPayload)(d,k)),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:F};f==="manual"&&(m.captureMethod=f),b!==void 0&&(m.checkoutMetadata=b),E&&(m.tagsData=E),y&&y.length>0&&(m.utmMetadata=y);let $=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions`,v=new AbortController,H=setTimeout(()=>v.abort(),K),l,u,I=this.merchantCredentials;try{let d=await fetch($,{method:"POST",headers:{"Content-Type":"application/json",...p(I)?{Authorization:ne(I)}:{},...te(_)?{[s.IDEMPOTENCY_KEY_HEADER]:_}:{}},body:JSON.stringify(m),signal:v.signal});l=d.status;try{u=await d.json()}catch{}}finally{clearTimeout(H)}if(l>=400)throw Z(l,u);if(l===201){let d=u?.data?.uuid,N=u?.data?.nonce;if(!d)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!N)throw new s.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(`${i.replace(/\/+$/,"")}/secure`);g.searchParams.set("id",d);for(let[L,V]of Object.entries(x))g.searchParams.set(L,V);return{result:{status:201,redirectUrl:g.toString(),nonce:N},body:u}}return l===204?{result:{status:204},body:u}:{result:{status:l},body:u}}requireStripe(){if(!this.stripe)throw ie();return this.stripe}normalizeStripeSession(e){let t={open:"open",complete:"complete",expired:"expired"};return{id:e.id,clientSecret:e.client_secret??"",mode:e.mode,status:t[e.status??"open"]??"open",amount:e.amount_total??0,currency:e.currency??"usd",metadata:e.metadata??{}}}async retrieveSession(e){let t=await this.requireStripe().checkout.sessions.retrieve(e);return this.normalizeStripeSession(t)}async expireSession(e){let t=await this.requireStripe().checkout.sessions.expire(e);return this.normalizeStripeSession(t)}async listLineItems(e){return(await this.requireStripe().checkout.sessions.listLineItems(e)).data.map(n=>({price:n.price?.id,quantity:n.quantity??1}))}constructWebhookEvent(e,t,n){let i=this.requireStripe().webhooks.constructEvent(e,t,n);return{id:i.id,type:i.type,data:i.data,created:i.created}}async createCustomer(e){let t=await this.requireStripe().customers.create({email:e.email,name:e.name,metadata:e.metadata});return{id:t.id,email:t.email??e.email,firstName:e.name?.split(" ")[0],lastName:e.name?.split(" ").slice(1).join(" ")}}async retrieveCustomer(e){let t=await this.requireStripe().customers.retrieve(e);if(t.deleted)throw new s.FloPayError(`Customer ${e} has been deleted`,"api_error",{code:"resource_missing"});return{id:t.id,email:t.email??"",firstName:t.name?.split(" ")[0],lastName:t.name?.split(" ").slice(1).join(" ")}}async updateCustomer(e,t){let n=await this.requireStripe().customers.update(e,{email:t.email,name:t.name,metadata:t.metadata});return{id:n.id,email:n.email??"",firstName:n.name?.split(" ")[0],lastName:n.name?.split(" ").slice(1).join(" ")}}};0&&(module.exports={FloPay,STRIPE_API_VERSION});
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, STRIPE_API_VERSION } from './flopay-node.js';
2
+ export { FloPay } from './flopay-node.js';
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{assertCaptureMethodEligible as j,buildProductPayload as z,FloPayError as i,foldIntoProducts as W,IDEMPOTENCY_KEY_HEADER as k,MAX_IDEMPOTENCY_KEY_LENGTH as Y,MERCHANT_AUTH_REQUIRED_CODE as N,resolveSessionCurrency as G,SDK_VERSION as M}from"@flopay/shared";import J from"stripe";var R="2026-04-22.dahlia";function g(r){return typeof r=="string"&&r.trim()?r:void 0}function O(r){if(typeof r=="string")return r.trim()?r:void 0;if(!Array.isArray(r))return;let e=r.filter(t=>typeof t=="string"&&t.trim().length>0);return e.length>0?e.join("; "):void 0}function Q(r,e){let t=e?.error,s=g(e?.code)??g(t?.code)??`http_${r}`,n=O(e?.message)??O(t?.message)??`Failed to create checkout session (HTTP ${r}).`;return new i(n,"api_error",{code:s,statusCode:r})}function X(r){for(let e of r){let t=e.charCodeAt(0);if(t<=8||t>=10&&t<=31||t===127)return!0}return!1}function Z(r){if(!r||r.trim()===""||r.length>Y||X(r))return!1;try{return new Headers({[k]:r}).get(k)===r}catch{return!1}}var ee=new Set(["confirm","auto"]),T=!1;function te(){T||(T=!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 h(r){return!!(r?.clientUuid&&r.apiToken)}function re(r){return`Basic ${Buffer.from(`${r.clientUuid}:${r.apiToken}`).toString("base64")}`}function se(){return new i("This operation needs a Stripe secret key. Pass one as the first constructor argument or as `stripeSecretKey`.","authentication_error",{code:"stripe_key_required"})}var P=class{constructor(e,t){let s=typeof e=="object"&&e!==null,n=s?e:t,a=s?void 0:e;if(!s&&!a)throw new i("A secret key is required to initialize the FloPay server SDK.","authentication_error");if(s&&!n?.stripeSecretKey&&!h(n?.merchantCredentials))throw new i("Pass `merchantCredentials`, `stripeSecretKey` or both to initialize the FloPay server SDK.","authentication_error");this.merchantCredentials=n?.merchantCredentials;let c=n?.stripeSecretKey??a;this.stripe=c?new J(c,{apiVersion:n?.apiVersion??R,appInfo:{name:"flopay-node",version:M}}):void 0,this.checkout={sessions:{create:this.createSession.bind(this),createOneClick:this.createOneClickSession.bind(this),retrieve:this.retrieveSession.bind(this),expire:this.expireSession.bind(this),listLineItems:this.listLineItems.bind(this)}},this.webhooks={constructEvent:this.constructWebhookEvent.bind(this)},this.customers={create:this.createCustomer.bind(this),retrieve:this.retrieveCustomer.bind(this),update:this.updateCustomer.bind(this)}}async createSession(e){let t=e.checkoutMode??"confirm";return ee.has(t)&&!h(this.merchantCredentials)&&te(),(await this.postSession(e,t)).result}async createOneClickSession(e){let t=this.merchantCredentials;if(!h(t))throw new i("checkout.sessions.createOneClick needs `merchantCredentials` ({ clientUuid, apiToken }) on the FloPay constructor.","authentication_error",{code:"merchant_credentials_required"});if(e.clientId!==t.clientUuid)throw new i("checkout.sessions.createOneClick: `clientId` must match `merchantCredentials.clientUuid`.","validation_error",{code:"client_id_mismatch",param:"clientId"});let{result:s,body:n}=await this.postSession(e,"confirm");if(g(n?.autoProcessingError?.gatewayErrorCode)===N)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:N,statusCode:s.status});let a=n?.data?.uuid,c="nonce"in s?s.nonce:void 0;if(s.status!==201||!a||!c)throw new i(`checkout.sessions.createOneClick expected a created session (HTTP 201), got HTTP ${s.status}.`,"api_error",{code:`http_${s.status}`,statusCode:s.status});return{sessionId:a,nonce:c}}async postSession(e,t){let{billingApiUrl:s,checkoutBaseUrl:n,items:a=[],subscriptions:c=[],products:A,account:o,successUrl:U,cancelUrl:q,captureMethod:p,couponCodes:F=[],checkoutMetadata:w,tagsData:b,redirectParams:x={},timeoutMs:K=12e3,clientId:B,currency:D,utmMetadata:C,idempotencyKey:E}=e,f=A??W(a,c);j({captureMethod:p,products:f});let y=G(D,a,c,f);if(!y)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 m={clientId:B,checkoutVersion:M,successUrl:U,cancelUrl:q,currency:y,checkoutMode:t,products:f.map(d=>z(d,y)),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:F};p==="manual"&&(m.captureMethod=p),w!==void 0&&(m.checkoutMetadata=w),b&&(m.tagsData=b),C&&C.length>0&&(m.utmMetadata=C);let $=`${s.replace(/\/+$/,"")}/v1/checkouts/sessions`,_=new AbortController,H=setTimeout(()=>_.abort(),K),l,u,v=this.merchantCredentials;try{let d=await fetch($,{method:"POST",headers:{"Content-Type":"application/json",...h(v)?{Authorization:re(v)}:{},...Z(E)?{[k]:E}:{}},body:JSON.stringify(m),signal:_.signal});l=d.status;try{u=await d.json()}catch{}}finally{clearTimeout(H)}if(l>=400)throw Q(l,u);if(l===201){let d=u?.data?.uuid,I=u?.data?.nonce;if(!d)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!I)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 S=new URL(`${n.replace(/\/+$/,"")}/secure`);S.searchParams.set("id",d);for(let[L,V]of Object.entries(x))S.searchParams.set(L,V);return{result:{status:201,redirectUrl:S.toString(),nonce:I},body:u}}return l===204?{result:{status:204},body:u}:{result:{status:l},body:u}}requireStripe(){if(!this.stripe)throw se();return this.stripe}normalizeStripeSession(e){let t={open:"open",complete:"complete",expired:"expired"};return{id:e.id,clientSecret:e.client_secret??"",mode:e.mode,status:t[e.status??"open"]??"open",amount:e.amount_total??0,currency:e.currency??"usd",metadata:e.metadata??{}}}async retrieveSession(e){let t=await this.requireStripe().checkout.sessions.retrieve(e);return this.normalizeStripeSession(t)}async expireSession(e){let t=await this.requireStripe().checkout.sessions.expire(e);return this.normalizeStripeSession(t)}async listLineItems(e){return(await this.requireStripe().checkout.sessions.listLineItems(e)).data.map(s=>({price:s.price?.id,quantity:s.quantity??1}))}constructWebhookEvent(e,t,s){let n=this.requireStripe().webhooks.constructEvent(e,t,s);return{id:n.id,type:n.type,data:n.data,created:n.created}}async createCustomer(e){let t=await this.requireStripe().customers.create({email:e.email,name:e.name,metadata:e.metadata});return{id:t.id,email:t.email??e.email,firstName:e.name?.split(" ")[0],lastName:e.name?.split(" ").slice(1).join(" ")}}async retrieveCustomer(e){let t=await this.requireStripe().customers.retrieve(e);if(t.deleted)throw new i(`Customer ${e} has been deleted`,"api_error",{code:"resource_missing"});return{id:t.id,email:t.email??"",firstName:t.name?.split(" ")[0],lastName:t.name?.split(" ").slice(1).join(" ")}}async updateCustomer(e,t){let s=await this.requireStripe().customers.update(e,{email:t.email,name:t.name,metadata:t.metadata});return{id:s.id,email:s.email??"",firstName:s.name?.split(" ")[0],lastName:s.name?.split(" ").slice(1).join(" ")}}};export{P as FloPay,R as STRIPE_API_VERSION};
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": "1.20.14",
3
+ "version": "2.0.0",
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": "1.20.14",
30
- "stripe": "^22.6.2"
29
+ "@flopay/shared": "2.0.0"
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"