FloPay (Node)
Server-side FloPay SDK for checkout session management, customer operations, and webhook handling.
FloPay
Server-side FloPay SDK. Supports checkout session creation via the billing API, direct Stripe operations for customers, and webhook event construction.
import { FloPay } from '@flopay/node';Constructor
new FloPay(secretKey: string, options?: FloPayNodeOptions)| Parameter | Type | Required | Description |
|---|---|---|---|
secretKey | string | Yes | Your Stripe secret key (e.g. sk_test_...). |
options | FloPayNodeOptions | No | Additional configuration. |
FloPayNodeOptions:
| Name | Type | Description |
|---|---|---|
apiVersion | string | API version override. |
stripeSecretKey | string | Stripe secret key (when using Stripe-specific operations). |
merchantCredentials | { clientUuid: string; apiToken: string } | Your merchant credentials: the client identifier and an API token from the API tokens page. Sent on every session create and required by checkout.sessions.createOneClick. Keep them on your server. |
Throws: FloPayError with type 'authentication_error' if secretKey is empty.
const flopay = new FloPay('sk_test_...');You can also pass a single options object. This form may omit the Stripe key: session creates still work, and the Stripe-only operations throw a FloPayError.
const flopay = new FloPay({
merchantCredentials: {
clientUuid: process.env.FLOPAY_CLIENT_ID!,
apiToken: process.env.FLOPAY_API_TOKEN!,
},
});checkout.sessions
create
Create a checkout session via the billing API. Posts to {billingApiUrl}/v1/checkouts/sessions.
checkout.sessions.create(params: CreateSessionParams): Promise<CheckoutSessionResult>| Parameter | Type | Required | Description |
|---|---|---|---|
params | CreateSessionParams | Yes | See CreateSessionParams. |
Use the optional checkoutMetadata map for safe merchant correlation values. See preserve checkout context with metadata for the Node example and lifecycle behavior.
Returns: Promise<CheckoutSessionResult>
{ status: 201, redirectUrl: string }-- session created, redirect URL available.{ status: 204 }-- payment method already on file.{ status: number }-- other status.
const result = await flopay.checkout.sessions.create({
billingApiUrl: 'https://billing.example.com',
checkoutBaseUrl: 'https://checkout.example.com',
clientId: 'client_123',
currency: 'USD',
products: [{ code: 'pro_plan', totalAmount: 49.99 }],
account: { userId: 'user_1', email: 'user@example.com' },
successUrl: '/success',
cancelUrl: '/cancel',
});Pass captureMethod: 'manual' to create an eligible item-only card authorisation. Omitting it preserves immediate capture, which remains the default. An authorised checkout reports status: 'authorized' with paymentId and authorizationExpiresAt through the checkout result.
Capture is not an SDK method. Call PUT /v1/payments/{paymentId}/capture from a trusted server with merchant authentication and a stable Idempotency-Key; see the payments REST reference.
Session-level currency is required. The SDK throws FloPayError({ type: 'validation_error', code: 'CurrencyRequired' }) synchronously — before the HTTP request — when neither the session-level currency nor any per-line currency resolves. Pass currency at the top of the session for the cleanest behavior.
The create response carries a nonce that authenticates every subsequent /v1/checkouts/* call as the x-checkout-session-token header. Forward it to your client (or your server-side continuation calls) and echo it on each request. See the Checkout session token guide.
createOneClick
Mint a server-minted one-click session for the browser automatic payment button. This is the recommended way to start a one-click purchase. It always creates a confirm session, whatever checkoutMode you pass, and returns only what the browser needs.
checkout.sessions.createOneClick(params: CreateSessionParams): Promise<{ sessionId: string; nonce: string }>| Parameter | Type | Required | Description |
|---|---|---|---|
params | CreateSessionParams | Yes | Same shape as CreateSessionParams. The mode is always confirm. |
Returns: Promise<{ sessionId: string; nonce: string }>. Return both to the browser, where the button's getSession resolves to them.
The create is sent with the merchantCredentials you passed to the constructor, so the session keeps its one-click mode. Create the client identifier and API token on the API tokens page and keep the token in your server's secret storage.
Take the buyer (account) from your own login session on the server, never from the request body. The browser only asks for a session; your server decides who is buying.
export async function POST() {
const user = await getCurrentUser(); // your own login session
if (!user) return new Response(null, { status: 401 });
const { sessionId, nonce } = await flopay.checkout.sessions.createOneClick({
billingApiUrl: 'https://billing.example.com',
checkoutBaseUrl: 'https://checkout.example.com',
clientId: process.env.FLOPAY_CLIENT_ID!,
currency: 'USD',
products: [{ code: 'upsell_ai_pack' }],
account: { userId: user.id, email: user.email },
successUrl: 'https://shop.example.com/success',
cancelUrl: 'https://shop.example.com/cancel',
});
return Response.json({ sessionId, nonce });
}A session created without merchant credentials, such as a keyless Auto or Confirm create from the browser, falls back to Full checkout and reports merchant_auth_required. Use createOneClick with merchantCredentials to keep one-click.
retrieve
Retrieve a checkout session from Stripe by ID.
checkout.sessions.retrieve(id: string): Promise<CheckoutSession>| Parameter | Type | Required | Description |
|---|---|---|---|
id | string | Yes | Stripe checkout session ID. |
Returns: Promise<CheckoutSession> -- normalized session object.
const session = await flopay.checkout.sessions.retrieve('cs_test_xxx');
console.log(session.status); // 'open' | 'complete' | 'expired'expire
Expire an open checkout session on Stripe.
checkout.sessions.expire(id: string): Promise<CheckoutSession>| Parameter | Type | Required | Description |
|---|---|---|---|
id | string | Yes | Stripe checkout session ID. |
Returns: Promise<CheckoutSession> -- the expired session.
listLineItems
List line items for a Stripe checkout session.
checkout.sessions.listLineItems(id: string): Promise<LineItem[]>| Parameter | Type | Required | Description |
|---|---|---|---|
id | string | Yes | Stripe checkout session ID. |
Returns: Promise<LineItem[]> -- array of line items with price and quantity.
const items = await flopay.checkout.sessions.listLineItems('cs_test_xxx');
// [{ price: 'price_xxx', quantity: 1 }]customers
create
Create a customer on Stripe.
customers.create(params: CreateCustomerParams): Promise<Customer>| Parameter | Type | Required | Description |
|---|---|---|---|
params.email | string | Yes | Customer email. |
params.name | string | No | Customer full name. |
params.metadata | Record<string, string> | No | Arbitrary metadata. |
Returns: Promise<Customer>
const customer = await flopay.customers.create({
email: 'user@example.com',
name: 'Jane Doe',
});retrieve
Retrieve a customer from Stripe by ID.
customers.retrieve(id: string): Promise<Customer>| Parameter | Type | Required | Description |
|---|---|---|---|
id | string | Yes | Stripe customer ID. |
Returns: Promise<Customer>
Throws: FloPayError with type 'api_error' and code 'resource_missing' if the customer has been deleted.
update
Update a customer on Stripe.
customers.update(id: string, params: UpdateCustomerParams): Promise<Customer>| Parameter | Type | Required | Description |
|---|---|---|---|
id | string | Yes | Stripe customer ID. |
params.email | string | No | Updated email. |
params.name | string | No | Updated name. |
params.metadata | Record<string, string> | No | Updated metadata. |
Returns: Promise<Customer>
const updated = await flopay.customers.update('cus_xxx', {
name: 'Jane Smith',
});webhooks
constructEvent
Construct and verify a direct Stripe webhook event from a raw payload and Stripe signature. This method does not verify Flo's normalized outbound merchant webhooks or their Flo-Signature header; use the Flo webhook delivery contract for those events.
webhooks.constructEvent(
payload: string | Buffer,
signature: string,
secret: string
): WebhookEvent| Parameter | Type | Required | Description |
|---|---|---|---|
payload | string | Buffer | Yes | Raw request body. |
signature | string | Yes | Value of Stripe's Stripe-Signature header. |
secret | string | Yes | Stripe webhook endpoint secret (for example whsec_...). |
Returns: WebhookEvent -- verified event with id, type, data, and created.
Throws: If the signature verification fails.
import { FloPay } from '@flopay/node';
const flopay = new FloPay('sk_test_...');
// In a direct Stripe webhook handler:
export async function POST(request: Request) {
const payload = await request.text();
const stripeSignature = request.headers.get('stripe-signature');
if (!stripeSignature) {
return new Response('Missing Stripe signature', { status: 400 });
}
let event;
try {
event = flopay.webhooks.constructEvent(
payload,
stripeSignature,
process.env.STRIPE_WEBHOOK_SECRET!
);
} catch (error) {
if (
error instanceof Error &&
'type' in error &&
error.type === 'StripeSignatureVerificationError'
) {
return new Response('Invalid Stripe signature', { status: 400 });
}
throw error;
}
console.log(event.type);
return new Response(null, { status: 204 });
}