Official Node.js SDK for Bear Billing - Margin intelligence and billing for AI companies
npm install @bearbilling/node-sdkOfficial Node.js SDK for Bear Billing - Margin intelligence and billing for AI companies.
``bash`
npm install @bearbilling/node-sdk
> Note: SDK is currently in alpha. Install with npm install @bearbilling/node-sdk@alpha when published.
`typescript
import { BearBilling } from '@bearbilling/node-sdk';
// Initialize client
const bearBilling = new BearBilling({
apiKey: process.env.BEAR_BILLING_API_KEY,
});
// Create a customer
const customer = await bearBilling.customers.create({
email: 'founder@ai-startup.com',
name: 'AI Startup Inc',
metadata: {
aiProvider: 'openai',
monthlyBudget: 5000,
}
});
// Create a subscription
const subscription = await bearBilling.subscriptions.create({
organizationId: customer.id,
planId: 'plan_pro_monthly',
billingCycle: 'monthly',
startDate: new Date().toISOString(),
});
// Track AI usage
const result = await bearBilling.usage.record({
eventType: 'token_usage',
metricName: 'llm_tokens',
quantity: 150000,
subscriptionId: subscription.id,
idempotencyKey: call-${Date.now()}, // Recommended: prevents duplicate billing
metadata: {
model: 'gpt-4-turbo',
provider: 'openai',
providerCostUsd: 4.50,
}
});
if (!result.recorded) {
console.log('Duplicate event skipped');
}
`
The SDK provides comprehensive usage tracking for AI billing:
`typescript
const result = await bearBilling.usage.record({
eventType: 'token_usage', // Required: Type of event
metricName: 'llm_tokens_input', // Required: Metric being tracked
quantity: 1500, // Required: Amount consumed
subscriptionId: 'sub_123', // Optional: For multi-subscription orgs
idempotencyKey: 'unique-key', // Recommended: Prevents duplicates
metadata: { // Optional: Additional context
model: 'claude-3-haiku',
provider: 'anthropic',
}
});
console.log(result.eventId); // Unique event ID
console.log(result.recorded); // true if new, false if duplicate
`
`typescript`
const events = await bearBilling.usage.query({
subscriptionId: 'sub_123',
metricName: 'llm_tokens_input',
startDate: '2024-01-01',
endDate: '2024-01-31',
limit: 100,
});
`typescript`
const aggregation = await bearBilling.usage.aggregation({
subscriptionId: 'sub_123',
startDate: '2024-01-01',
endDate: '2024-01-31',
});
`typescript`
const summary = await bearBilling.usage.summary({
subscriptionId: 'sub_123',
startDate: '2024-01-01',
endDate: '2024-01-31',
});
`typescript
import { BearBilling, BearBillingApiError } from '@bearbilling/node-sdk';
try {
const customer = await bearBilling.customers.create({
email: 'founder@ai-startup.com',
name: 'AI Startup Inc',
});
} catch (error) {
if (error instanceof BearBillingApiError) {
switch (error.code) {
case 'invalid_email':
console.error('Invalid email format');
break;
case 'duplicate_customer':
console.error('Customer already exists');
break;
case 'rate_limit_exceeded':
console.error(Rate limit hit, retry after ${error.retryAfter} seconds);Error: ${error.message}
break;
case 'authentication_error':
console.error('Invalid API key');
break;
default:
console.error();`
}
}
}
`typescript`
const bearBilling = new BearBilling({
apiKey: 'bb_live_...', // Required
baseUrl: 'https://api.bearbilling.com', // Optional (default)
timeout: 30000, // Optional: 30s default
});
| Method | Description |
|--------|-------------|
| customers.create(data) | Create a new customer |customers.retrieve(id)
| | Get a customer by ID |customers.update(id, data)
| | Update a customer |customers.list(params?)
| | List all customers |
| Method | Description |
|--------|-------------|
| subscriptions.create(data) | Create a new subscription |subscriptions.retrieve(id)
| | Get a subscription by ID |subscriptions.update(id, data)
| | Update a subscription |subscriptions.cancel(id)
| | Cancel a subscription |subscriptions.list(params?)
| | List all subscriptions |
| Method | Description |
|--------|-------------|
| usage.record(data) | Record a usage event |usage.query(params?)
| | Query usage events |usage.aggregation(params?)
| | Get aggregated usage by metric |usage.summary(params?)
| | Get high-level usage summary |
This SDK is written in TypeScript and includes full type definitions.
`typescript`
import {
BearBilling,
BearBillingConfig,
Customer,
CustomerCreateInput,
Subscription,
SubscriptionCreateInput,
UsageRecordInput,
UsageRecordResponse,
BearBillingApiError
} from '@bearbilling/node-sdk';
`typescript``
interface UsageRecordInput {
eventType: string; // e.g., 'token_usage', 'api_request'
metricName: string; // e.g., 'llm_tokens', 'api_calls'
quantity: number; // Amount consumed
subscriptionId?: string; // Optional: For multi-subscription orgs
eventTimestamp?: string; // Optional: Defaults to now
idempotencyKey?: string; // Recommended: Prevents duplicates
metadata?: Record
}
- Node.js >= 18.0.0
Full documentation available at docs.bearbilling.com
- Email: support@bearbilling.com
- Discord: discord.gg/bearbilling
- Docs: docs.bearbilling.com
MIT