@flopay/node 1.16.3 → 1.16.5

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
@@ -28,6 +28,29 @@ 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`.
32
+
33
+ ```ts
34
+ import { FloPay } from '@flopay/node';
35
+
36
+ const flopay = new FloPay({
37
+ merchantCredentials: {
38
+ clientUuid: process.env.FLOPAY_CLIENT_UUID!,
39
+ apiToken: process.env.FLOPAY_API_TOKEN!,
40
+ },
41
+ });
42
+ ```
43
+
44
+ When `merchantCredentials` are configured, every session create sends them as HTTP Basic credentials. They never appear in an error message.
45
+
46
+ ### Secure one-click sessions
47
+
48
+ `flopay.checkout.sessions.createOneClick()` mints a credentialed Confirm session for `FloPayAutomaticPaymentButton`'s `getSession` in `@flopay/react`. It takes the same `CreateSessionParams` as `create()`, always creates a `'confirm'` session whatever `checkoutMode` you pass, and resolves with exactly `{ sessionId, nonce }`: return that to the browser and nothing else. It throws before any request when no `merchantCredentials` are configured or when `clientId` is not your `merchantCredentials.clientUuid`, and it throws `merchant_auth_required` when the billing API did not accept the credentials and created a Full checkout instead.
49
+
50
+ Expose it from a route your browser calls on click. Take the buyer from your own login session (the authenticated user behind your session cookie), never from the request body or query string: the route decides who is charged, not the browser.
51
+
52
+ Keyless confirm and auto creates (`create()` with `checkoutMode` `'confirm'` or `'auto'` and no `merchantCredentials`) are deprecated: the billing API may create a Full checkout for them instead. The first one in a process logs a one-time `console.warn` pointing at `createOneClick`. Full-mode creates and credentialed creates do not warn.
53
+
31
54
  ### Create a checkout session
32
55
 
33
56
  `flopay.checkout.sessions.create()` posts to the billing API's `POST /v1/checkouts/sessions` and resolves with a `CheckoutSessionResult`:
@@ -83,6 +106,47 @@ Deleting a saved method works the same way for every type, with the same `Paymen
83
106
 
84
107
  ## Examples
85
108
 
109
+ A `getSession` route for `FloPayAutomaticPaymentButton`, built on `createOneClick`. The buyer comes from your own login session, never from the request body:
110
+
111
+ ```ts
112
+ import { FloPay } from '@flopay/node';
113
+
114
+ function requiredEnv(name: string): string {
115
+ const value = process.env[name];
116
+ if (!value) throw new Error(`${name} is not set`);
117
+ return value;
118
+ }
119
+
120
+ const flopay = new FloPay({
121
+ merchantCredentials: {
122
+ clientUuid: requiredEnv('FLOPAY_CLIENT_UUID'),
123
+ apiToken: requiredEnv('FLOPAY_API_TOKEN'),
124
+ },
125
+ });
126
+
127
+ /** The buyer your own auth resolved from the login session cookie. */
128
+ interface LoggedInBuyer {
129
+ id: string;
130
+ email: string;
131
+ }
132
+
133
+ // Handler for your `POST /api/flopay/one-click-session` route, mounted behind your own auth
134
+ // middleware. It takes the logged-in buyer, never anything the browser sent.
135
+ export async function oneClickSessionHandler(buyer: LoggedInBuyer) {
136
+ // Resolves with exactly { sessionId, nonce }: send it back as the route's JSON body.
137
+ return flopay.checkout.sessions.createOneClick({
138
+ billingApiUrl: 'https://billing.example.com',
139
+ checkoutBaseUrl: 'https://checkout.example.com',
140
+ clientId: requiredEnv('FLOPAY_CLIENT_UUID'),
141
+ currency: 'USD',
142
+ items: [{ providerItemId: 'prod_upsell', totalAmount: 19.99 }],
143
+ account: { userId: buyer.id, email: buyer.email },
144
+ successUrl: 'https://shop.example.com/success',
145
+ cancelUrl: 'https://shop.example.com/cancel',
146
+ });
147
+ }
148
+ ```
149
+
86
150
  Create a checkout session and redirect the buyer:
87
151
 
88
152
  ```ts
@@ -241,7 +305,7 @@ console.log(updated.email, session.status, session.amount);
241
305
 
242
306
  | Export | Description |
243
307
  |--------|-------------|
244
- | `FloPay` | Server-side client: `new FloPay(secretKey, options?)` with a Stripe secret key (`sk_test_...` or `sk_live_...`) |
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 |
245
309
  | `FloPayNodeOptions` | Constructor options |
246
310
  | `STRIPE_API_VERSION` | `'2026-04-22.dahlia'`, the default Stripe API version for direct Stripe operations |
247
311
 
@@ -251,12 +315,14 @@ console.log(updated.email, session.status, session.amount);
251
315
  |--------|------|-------------|
252
316
  | `apiVersion` | `string?` | Stripe API version override for direct Stripe operations |
253
317
  | `stripeSecretKey` | `string?` | Stripe secret key for direct Stripe operations, instead of the constructor key |
318
+ | `merchantCredentials` | `MerchantCredentials?` | `{ clientUuid, apiToken }`. Sent as HTTP Basic credentials on every session create, and required by `checkout.sessions.createOneClick()` |
254
319
 
255
320
  ### FloPay methods
256
321
 
257
322
  | Method | Returns | Description |
258
323
  |--------|---------|-------------|
259
324
  | `checkout.sessions.create(params)` | `Promise<CheckoutSessionResult>` | Creates a session through the billing API (`POST /v1/checkouts/sessions`). Accepts `CreateSessionParams`. |
325
+ | `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`. |
260
326
  | `checkout.sessions.retrieve(id)` | `Promise<CheckoutSession>` | Retrieves and normalizes a Stripe checkout session |
261
327
  | `checkout.sessions.expire(id)` | `Promise<CheckoutSession>` | Expires a Stripe checkout session |
262
328
  | `checkout.sessions.listLineItems(id)` | `Promise<LineItem[]>` | Lists a Stripe checkout session's line items |
@@ -265,9 +331,11 @@ console.log(updated.email, session.status, session.amount);
265
331
  | `customers.update(id, params)` | `Promise<Customer>` | Updates a Stripe customer |
266
332
  | `webhooks.constructEvent(payload, signature, secret)` | `WebhookEvent` | Verifies and parses a Stripe webhook event |
267
333
 
268
- The parameter and result types (`CreateSessionParams`, `CheckoutSessionResult`, `CheckoutSession`, `Customer`, `LineItem`, `WebhookEvent`) are exported by `@flopay/shared`.
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.
269
337
 
270
- `@flopay/node` has no card-setup method and holds no merchant credential. `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.
338
+ `@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.
271
339
 
272
340
  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.
273
341
 
@@ -282,5 +350,9 @@ SDK validation and billing API failures are `FloPayError`s from `@flopay/shared`
282
350
  | 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`. |
283
351
  | `MissingCheckoutSessionToken` | `api_error` | The billing API created a session but returned no `nonce`, which means it is too old for this SDK. |
284
352
  | `resource_missing` | `api_error` | `customers.retrieve()` found a deleted customer. |
353
+ | `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
+ | `merchant_credentials_required` | `authentication_error` | `checkout.sessions.createOneClick()` was called on a client without `merchantCredentials`. Thrown before any request. |
355
+ | `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. |
285
357
 
286
- Constructing `FloPay` without a secret key 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.
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.
@@ -1,10 +1,12 @@
1
- import type { CheckoutSession, CheckoutSessionResult, CreateCustomerParams, CreateSessionParams, Customer, LineItem, UpdateCustomerParams, WebhookEvent } from '@flopay/shared';
1
+ import type { CheckoutSession, CheckoutSessionResult, CreateCustomerParams, CreateOneClickSessionParams, CreateSessionParams, Customer, LineItem, MerchantCredentials, OneClickSession, UpdateCustomerParams, WebhookEvent } from '@flopay/shared';
2
2
  export declare const STRIPE_API_VERSION = "2026-04-22.dahlia";
3
3
  /** Options for the FloPay Node SDK constructor. */
4
4
  export interface FloPayNodeOptions {
5
5
  apiVersion?: string;
6
6
  /** Stripe secret key, required when using Stripe-specific operations. */
7
7
  stripeSecretKey?: string;
8
+ /** Merchant credentials sent on every session create and required by `createOneClick`. */
9
+ merchantCredentials?: MerchantCredentials;
8
10
  }
9
11
  /**
10
12
  * Server-side FloPay SDK.
@@ -38,11 +40,15 @@ export interface FloPayNodeOptions {
38
40
  * ```
39
41
  */
40
42
  export declare class FloPay {
43
+ /** Built when a Stripe key is configured; Stripe-only operations throw without it. */
41
44
  private readonly stripe;
45
+ private readonly merchantCredentials;
42
46
  readonly checkout: {
43
47
  sessions: {
44
48
  /** Create a checkout session via the billing API. */
45
49
  create: (params: CreateSessionParams) => Promise<CheckoutSessionResult>;
50
+ /** Mint a credentialed Confirm session for a browser one-click button. */
51
+ createOneClick: (params: CreateOneClickSessionParams) => Promise<OneClickSession>;
46
52
  /** Retrieve a checkout session from Stripe. */
47
53
  retrieve: (id: string) => Promise<CheckoutSession>;
48
54
  /** Expire a checkout session on Stripe. */
@@ -59,7 +65,13 @@ export declare class FloPay {
59
65
  retrieve: (id: string) => Promise<Customer>;
60
66
  update: (id: string, params: UpdateCustomerParams) => Promise<Customer>;
61
67
  };
62
- constructor(secretKey: string, options?: FloPayNodeOptions);
68
+ /**
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`.
73
+ */
74
+ constructor(secretKeyOrOptions: string | FloPayNodeOptions, options?: FloPayNodeOptions);
63
75
  /**
64
76
  * Create a checkout session via the billing API.
65
77
  *
@@ -68,6 +80,16 @@ export declare class FloPay {
68
80
  * the session UUID for redirect.
69
81
  */
70
82
  private createSession;
83
+ /**
84
+ * Mint a credentialed Confirm session for a browser one-click button.
85
+ *
86
+ * Always creates a `'confirm'` session, whatever `checkoutMode` the caller
87
+ * passes, and returns only what the browser needs: `{ sessionId, nonce }`.
88
+ */
89
+ private createOneClickSession;
90
+ /** Posts a session create to the billing API and maps its answer. */
91
+ private postSession;
92
+ private requireStripe;
71
93
  private normalizeStripeSession;
72
94
  private retrieveSession;
73
95
  private expireSession;
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var $=Object.create;var m=Object.defineProperty;var z=Object.getOwnPropertyDescriptor;var H=Object.getOwnPropertyNames;var K=Object.getPrototypeOf,q=Object.prototype.hasOwnProperty;var W=(r,e)=>{for(var t in e)m(r,t,{get:e[t],enumerable:!0})},v=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of H(e))!q.call(r,n)&&n!==t&&m(r,n,{get:()=>e[n],enumerable:!(i=z(e,n))||i.enumerable});return r};var Y=(r,e,t)=>(t=r!=null?$(K(r)):{},v(e||!r||!r.__esModule?m(t,"default",{value:r,enumerable:!0}):t,r)),G=r=>v(m({},"__esModule",{value:!0}),r);var Z={};W(Z,{FloPay:()=>l,STRIPE_API_VERSION:()=>C});module.exports=G(Z);var s=require("@flopay/shared"),_=Y(require("stripe"),1),C="2026-04-22.dahlia";function I(r){return typeof r=="string"&&r.trim()?r:void 0}function N(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 J(r,e){let t=e?.error,i=I(e?.code)??I(t?.code)??`http_${r}`,n=N(e?.message)??N(t?.message)??`Failed to create checkout session (HTTP ${r}).`;return new s.FloPayError(n,"api_error",{code:i,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 Q(r){if(!r||r.trim()===""||r.length>s.MAX_IDEMPOTENCY_KEY_LENGTH||X(r))return!1;try{return new Headers({[s.IDEMPOTENCY_KEY_HEADER]:r}).get(s.IDEMPOTENCY_KEY_HEADER)===r}catch{return!1}}var l=class{constructor(e,t){if(!e)throw new s.FloPayError("A secret key is required to initialize the FloPay server SDK.","authentication_error");this.stripe=new _.default(t?.stripeSecretKey??e,{apiVersion:t?.apiVersion??C,appInfo:{name:"flopay-node",version:s.SDK_VERSION}}),this.checkout={sessions:{create:this.createSession.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{billingApiUrl:t,checkoutBaseUrl:i,items:n=[],subscriptions:S=[],products:A,account:o,successUrl:M,cancelUrl:R,checkoutMode:T="confirm",captureMethod:p,couponCodes:U=[],checkoutMetadata:k,tagsData:P,redirectParams:x={},timeoutMs:O=12e3,clientId:V,currency:L,utmMetadata:h,idempotencyKey:b}=e,f=A??(0,s.foldIntoProducts)(n,S);(0,s.assertCaptureMethodEligible)({captureMethod:p,products:f});let y=(0,s.resolveSessionCurrency)(L,n,S,f);if(!y)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 u={clientId:V,checkoutVersion:s.SDK_VERSION,successUrl:M,cancelUrl:R,currency:y,checkoutMode:T,products:f.map(a=>(0,s.buildProductPayload)(a,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:U};p==="manual"&&(u.captureMethod=p),k!==void 0&&(u.checkoutMetadata=k),P&&(u.tagsData=P),h&&h.length>0&&(u.utmMetadata=h);let D=`${t.replace(/\/+$/,"")}/v1/checkouts/sessions`,w=new AbortController,j=setTimeout(()=>w.abort(),O),c,d;try{let a=await fetch(D,{method:"POST",headers:{"Content-Type":"application/json",...Q(b)?{[s.IDEMPOTENCY_KEY_HEADER]:b}:{}},body:JSON.stringify(u),signal:w.signal});c=a.status;try{d=await a.json()}catch{}}finally{clearTimeout(j)}if(c>=400)throw J(c,d);if(c===201){let a=d?.data?.uuid,E=d?.data?.nonce;if(!a)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!E)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",a);for(let[F,B]of Object.entries(x))g.searchParams.set(F,B);return{status:201,redirectUrl:g.toString(),nonce:E}}return c===204?{status:204}:{status:c}}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.stripe.checkout.sessions.retrieve(e);return this.normalizeStripeSession(t)}async expireSession(e){let t=await this.stripe.checkout.sessions.expire(e);return this.normalizeStripeSession(t)}async listLineItems(e){return(await this.stripe.checkout.sessions.listLineItems(e)).data.map(i=>({price:i.price?.id,quantity:i.quantity??1}))}constructWebhookEvent(e,t,i){let n=this.stripe.webhooks.constructEvent(e,t,i);return{id:n.id,type:n.type,data:n.data,created:n.created}}async createCustomer(e){let t=await this.stripe.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.stripe.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 i=await this.stripe.customers.update(e,{email:t.email,name:t.name,metadata:t.metadata});return{id:i.id,email:i.email??"",firstName:i.name?.split(" ")[0],lastName:i.name?.split(" ").slice(1).join(" ")}}};0&&(module.exports={FloPay,STRIPE_API_VERSION});
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});
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{assertCaptureMethodEligible as B,buildProductPayload as $,FloPayError as u,foldIntoProducts as z,IDEMPOTENCY_KEY_HEADER as y,MAX_IDEMPOTENCY_KEY_LENGTH as H,resolveSessionCurrency as K,SDK_VERSION as E}from"@flopay/shared";import q from"stripe";var N="2026-04-22.dahlia";function v(r){return typeof r=="string"&&r.trim()?r:void 0}function I(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 W(r,e){let t=e?.error,s=v(e?.code)??v(t?.code)??`http_${r}`,i=I(e?.message)??I(t?.message)??`Failed to create checkout session (HTTP ${r}).`;return new u(i,"api_error",{code:s,statusCode:r})}function Y(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 G(r){if(!r||r.trim()===""||r.length>H||Y(r))return!1;try{return new Headers({[y]:r}).get(y)===r}catch{return!1}}var g=class{constructor(e,t){if(!e)throw new u("A secret key is required to initialize the FloPay server SDK.","authentication_error");this.stripe=new q(t?.stripeSecretKey??e,{apiVersion:t?.apiVersion??N,appInfo:{name:"flopay-node",version:E}}),this.checkout={sessions:{create:this.createSession.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{billingApiUrl:t,checkoutBaseUrl:s,items:i=[],subscriptions:C=[],products:_,account:n,successUrl:A,cancelUrl:M,checkoutMode:R="confirm",captureMethod:m,couponCodes:T=[],checkoutMetadata:S,tagsData:k,redirectParams:U={},timeoutMs:x=12e3,clientId:O,currency:V,utmMetadata:l,idempotencyKey:P}=e,p=_??z(i,C);B({captureMethod:m,products:p});let h=K(V,i,C,p);if(!h)throw new u("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 c={clientId:O,checkoutVersion:E,successUrl:A,cancelUrl:M,currency:h,checkoutMode:R,products:p.map(o=>$(o,h)),accountData:{userId:n.userId,firstName:n.firstName??null,lastName:n.lastName??null,email:n.email,country:n.country??null,gender:n.gender??null,city:n.city??null,state:n.state??null,zip:n.zip??null},couponCodes:T};m==="manual"&&(c.captureMethod=m),S!==void 0&&(c.checkoutMetadata=S),k&&(c.tagsData=k),l&&l.length>0&&(c.utmMetadata=l);let L=`${t.replace(/\/+$/,"")}/v1/checkouts/sessions`,b=new AbortController,D=setTimeout(()=>b.abort(),x),a,d;try{let o=await fetch(L,{method:"POST",headers:{"Content-Type":"application/json",...G(P)?{[y]:P}:{}},body:JSON.stringify(c),signal:b.signal});a=o.status;try{d=await o.json()}catch{}}finally{clearTimeout(D)}if(a>=400)throw W(a,d);if(a===201){let o=d?.data?.uuid,w=d?.data?.nonce;if(!o)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!w)throw new u("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 f=new URL(`${s.replace(/\/+$/,"")}/secure`);f.searchParams.set("id",o);for(let[j,F]of Object.entries(U))f.searchParams.set(j,F);return{status:201,redirectUrl:f.toString(),nonce:w}}return a===204?{status:204}:{status:a}}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.stripe.checkout.sessions.retrieve(e);return this.normalizeStripeSession(t)}async expireSession(e){let t=await this.stripe.checkout.sessions.expire(e);return this.normalizeStripeSession(t)}async listLineItems(e){return(await this.stripe.checkout.sessions.listLineItems(e)).data.map(s=>({price:s.price?.id,quantity:s.quantity??1}))}constructWebhookEvent(e,t,s){let i=this.stripe.webhooks.constructEvent(e,t,s);return{id:i.id,type:i.type,data:i.data,created:i.created}}async createCustomer(e){let t=await this.stripe.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.stripe.customers.retrieve(e);if(t.deleted)throw new u(`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.stripe.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{g as FloPay,N as STRIPE_API_VERSION};
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};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flopay/node",
3
- "version": "1.16.3",
3
+ "version": "1.16.5",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "publishConfig": {
@@ -26,7 +26,7 @@
26
26
  "dist"
27
27
  ],
28
28
  "dependencies": {
29
- "@flopay/shared": "1.16.3",
29
+ "@flopay/shared": "1.16.5",
30
30
  "stripe": "^22.6.2"
31
31
  },
32
32
  "devDependencies": {