flexprice-ts-sdk
v2.2.0
Published
TypeScript & JavaScript SDK for Flexprice usage-based billing infrastructure
Readme
@flexprice/sdk
Unofficial TypeScript & JavaScript SDK for Flexprice
A lightweight, fully typed, resilient client for the Flexprice metering & billing platform.
Features
- 100% Type-Safe: Full TypeScript auto-completion powered directly by Flexprice OpenAPI operations.
- Multi-Region Native: Built-in support for US (
us) and India (in) Flexprice Cloud clusters, with custom endpoint overrides for self-hosted instances. - AsyncIterable Streaming: Effortlessly paginate through large datasets using
for await (... of client.<resource>.list()). - Built-in Resilience: Automatic retries with exponential backoff for rate-limits (
429), server conflicts (409), and transient errors (5xx). - Zero Heavy Dependencies: Extremely lightweight with standard Web
fetchAPI compatibility.
Installation
npm install @flexprice/sdk
# or
pnpm add @flexprice/sdk
# or
yarn add @flexprice/sdkQuickstart
Initialize the unified Flexprice client to access all 7 core platform resources:
import { Flexprice } from "@flexprice/sdk";
const flexprice = new Flexprice({
apiKey: process.env.FLEXPRICE_API_KEY,
region: "in", // "in" (api.cloud.flexprice.io) or "us" (us.api.flexprice.io)
});
async function main() {
// 1. Create a customer
const customer = await flexprice.customers.create({
name: "Acme Enterprises",
email: "[email protected]",
external_id: "acme_tenant_101",
});
console.log(`Created customer: ${customer.id}`);
// 2. Create a subscription
const subscription = await flexprice.subscriptions.create({
customer_id: customer.id,
plan_id: "plan_pro_tier",
currency: "USD",
billing_period: "MONTHLY",
});
console.log(`Subscription status: ${subscription.status}`);
// 3. Ingest metered usage event
await flexprice.events.ingest({
event_name: "api_requests",
customer_id: customer.id,
properties: { tokens_used: 1500, model: "gpt-4o" },
timestamp: new Date().toISOString(),
});
}
main().catch(console.error);Core Resources
The SDK exposes 7 specialized resource modules attached to the Flexprice instance (or available as individual standalone imports):
1. Customers (flexprice.customers)
Create, update, search customers, and inspect customer entitlement state:
const customer = await flexprice.customers.create({
name: "Stark Industries",
email: "[email protected]",
external_id: "stark_001",
});
const search = await flexprice.customers.query({ limit: 10 });2. Metering & Events (flexprice.events)
Ingest single or bulk metered usage events and query usage analytics:
// Single event ingestion
await flexprice.events.ingest({
event_name: "vector_search",
customer_id: "cust_123",
properties: { query_count: 50 },
});
// Bulk event ingestion
await flexprice.events.ingestBulk([
{ event_name: "storage_gb", customer_id: "cust_123", properties: { size: 10 } },
{ event_name: "storage_gb", customer_id: "cust_456", properties: { size: 25 } },
]);3. Features & Entitlements (flexprice.features)
Define metered, boolean, static, and config features:
const feature = await flexprice.features.create({
name: "API Rate Limit",
lookup_key: "api_rate_limit",
type: "METERED",
});4. Plans & Prices (flexprice.plans & flexprice.prices)
Manage billing tiers, cloning, flat fees, and tiered usage pricing:
// Create bulk prices
await flexprice.prices.createBulk({
items: [
{
amount: "99",
currency: "usd",
type: "FIXED",
billing_period: "MONTHLY",
billing_period_count: 1,
invoice_cadence: "ADVANCE",
entity_type: "PLAN",
entity_id: "plan_123",
},
],
});5. Subscriptions (flexprice.subscriptions)
Manage customer subscription lifecycles, upgrades, add-ons, and plan change previews:
// Preview plan change proration impact
const preview = await flexprice.subscriptions.previewPlanChange("sub_123", {
target_plan_id: "plan_enterprise",
billing_cadence: "RECURRING",
billing_cycle: "anniversary",
billing_period: "MONTHLY",
billing_period_count: 1,
proration_behavior: "create_prorations",
});
console.log(`Credit amount: ${preview.proration_details?.credit_amount}`);6. Invoices (flexprice.invoices)
Preview, query, finalize, void, and pay invoices:
const invoices = await flexprice.invoices.query({
customer_id: "cust_123",
limit: 5,
});
// Finalize a draft invoice
await flexprice.invoices.finalize("inv_123");Streaming Auto-Pagination
Every listable resource provides an AsyncIterable method for smooth pagination:
// Automatically handles page offsets and limits in the background
for await (const subscription of flexprice.subscriptions.list({ limit: 25 })) {
console.log(`Sub ID: ${subscription.id}, Status: ${subscription.status}`);
}Client Configuration
| Option | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| apiKey | string | process.env.FLEXPRICE_API_KEY | Your Flexprice API key (sk_test_... or sk_live_...) |
| region | "us" \| "in" | "us" | Deployment cluster region ("us" or "in") |
| baseUrl | string | undefined | Custom base URL override for self-hosted instances |
| timeout | number | 10000 | HTTP request timeout in milliseconds |
| maxRetries | number | 3 | Maximum automatic retries for 429, 409, or 5xx errors |
| fetch | typeof fetch | globalThis.fetch | Custom fetch implementation |
Error Handling
All SDK errors inherit from FlexpriceError with HTTP status codes and endpoint context:
import { Flexprice, FlexpriceError } from "@flexprice/sdk";
try {
await flexprice.subscriptions.get("sub_non_existent");
} catch (error) {
if (error instanceof FlexpriceError) {
console.error(`Flexprice API Error (${error.status}):`, error.message);
console.error(`Endpoint: ${error.endpoint}, Request ID: ${error.requestId}`);
}
}License
MIT © Flexprice Community
