atehra-sdk
v2.0.0
Published
SDK TypeScript para Atehra API — wrapping automático de OpenAI, Anthropic e Gemini
Maintainers
Readme
atehra-sdk
TypeScript SDK for the Billing Infrastructure API — subscriptions, one-time payments, usage metering, LLM token tracking, and dunning in one client.
Install
npm install atehra-sdkQuick Start
import { AtheraClient } from "atehra-sdk"
const billing = new AtheraClient({
apiKey: "bill_xxx", // from POST /v1/tenants
baseUrl: "https://billing-api-production-409b.up.railway.app/v1",
})
// List plans
const plans = await billing.plans.list()
// Create a customer and start a subscription
const customer = await billing.customers.create({
externalId: "user_123",
email: "[email protected]",
name: "Jane Doe",
})
const session = await billing.checkout.createSession({
customerId: customer.id,
planId: "plan_id_here",
billingType: "PIX",
taxId: "000.000.000-00",
})
console.log(session.pixCopiaECola) // show QR to userAuthentication
Every request requires an API key obtained when creating a tenant:
curl -X POST https://your-api/v1/tenants \
-H "Content-Type: application/json" \
-d '{"name": "My SaaS", "email": "[email protected]"}'
# → { "apiKey": { "key": "bill_xxx" } }Pass the key in AtheraClient({ apiKey: "bill_xxx", baseUrl: "..." }). All requests send it as the x-api-key header automatically.
Resources
billing.plans
| Method | Description |
|--------|-------------|
| create(data) | Create a subscription or one-time plan |
| list() | List all plans |
| get(id) | Get plan by ID |
| update(id, data) | Update name, description, or price |
| delete(id) | Delete a plan |
const plan = await billing.plans.create({
name: "Pro",
slug: "pro",
price: 9900, // in cents (R$ 99,00)
type: "subscription",
interval: "month",
trialType: "time",
trialDays: 14,
})billing.customers
| Method | Description |
|--------|-------------|
| create(data) | Register a customer |
| list() | List all customers |
| get(id) | Get customer by ID |
| update(id, data) | Update email or name |
| delete(id) | Anonymize PII (LGPD-compliant) |
const customer = await billing.customers.create({
externalId: "user_123", // your internal user ID
email: "[email protected]",
name: "Jane Doe",
})billing.subscriptions
| Method | Description |
|--------|-------------|
| create(data) | Create subscription directly (no checkout) |
| get(customerId) | Get active subscription for customer |
| cancel(customerId) | Cancel active subscription |
| changePlan(customerId, planId) | Upgrade or downgrade plan |
| history(customerId) | Full subscription history |
billing.checkout
| Method | Description |
|--------|-------------|
| createSession(data) | Start a PIX, boleto, or credit card checkout |
| createLink(data) | Create a shareable checkout link |
| listLinks(planId?) | List checkout links |
| getLink(id) | Get checkout link by ID |
| deactivateLink(id) | Deactivate a checkout link |
// PIX checkout for a subscription
const session = await billing.checkout.createSession({
customerId: "cust_id",
planId: "plan_id",
billingType: "PIX",
taxId: "17006278643", // CPF required in production
})
// session.pixCopiaECola — paste into any bank app
// session.pixQrCodeBase64 — render as <img src={`data:image/png;base64,${...}`} />
// Shareable checkout link (no code integration needed)
const link = await billing.checkout.createLink({
planId: "plan_id",
name: "Black Friday",
successUrl: "https://yourapp.com/welcome",
maxUses: 100,
})
// share link.url → /checkout/link/{slug}billing.orders
| Method | Description |
|--------|-------------|
| list(filters?) | List orders (filter by status, customerId) |
| get(id) | Get order by ID |
| refund(id, value?) | Refund full or partial amount |
| cancel(id) | Cancel a pending order |
billing.usage
| Method | Description |
|--------|-------------|
| record(data) | Report a usage event |
| get(customerId) | Get current period usage for customer |
| listAll() | List all usage events for the tenant |
// Report API calls, tokens, requests — any metric
await billing.usage.record({
customerId: "cust_id",
type: "api_call",
quantity: 1,
})billing.billing
| Method | Description |
|--------|-------------|
| generateInvoice(customerId) | Generate invoice for current period |
| listInvoices(customerId) | List all invoices for customer |
| createPricingRule(data) | Create usage-based pricing rule |
| getPricingRules(planId) | Get pricing rules for a plan |
billing.entitlements
| Method | Description |
|--------|-------------|
| check(customerId, feature) | Check if customer has access to a feature |
| sync(customerId) | Sync entitlements from active subscription |
const { allowed, limit } = await billing.entitlements.check("cust_id", "exports")
if (!allowed) throw new Error("Upgrade required")billing.coupons
| Method | Description |
|--------|-------------|
| create(data) | Create a discount coupon |
| list() | List all coupons |
| get(id) | Get coupon by ID |
| deactivate(id) | Deactivate coupon |
| validate(data) | Validate coupon and get discount amount |
const coupon = await billing.coupons.create({
code: "LAUNCH50",
type: "percentage",
value: 50, // 50% off
maxUses: 200,
validUntil: "2026-12-31T23:59:59Z",
})billing.alerts
| Method | Description |
|--------|-------------|
| create(data) | Create a usage cost alert |
| list() | List all alerts |
| delete(id) | Delete an alert |
billing.metrics
| Method | Description |
|--------|-------------|
| overview() | MRR, ARR, active subs, churn, ARPU, LTV |
| mrr() | Monthly recurring revenue breakdown |
| churn(period?) | Churn rate for a period |
| revenue(period?) | Revenue over time |
| arpu(period?) | Average revenue per user |
| ltv() | Lifetime value estimate |
billing.webhooks
| Method | Description |
|--------|-------------|
| create(data) | Register a webhook endpoint |
| list() | List registered endpoints |
| delete(id) | Remove an endpoint |
billing.audit
| Method | Description |
|--------|-------------|
| list(filters?) | List audit log entries |
LLM Wrappers
Automatically report token consumption to your billing system — no manual tracking needed.
OpenAI
import OpenAI from "openai"
import { AtheraClient } from "atehra-sdk"
const billing = new AtheraClient({ apiKey: "bill_xxx", baseUrl: "..." })
const openai = billing.wrapOpenAI(new OpenAI(), { customerId: "cust_123" })
// Tokens reported automatically — your code doesn't change
const response = await openai.chat.completions.create({
model: "gpt-4o",
messages: [{ role: "user", content: "Hello" }],
})Anthropic
import Anthropic from "@anthropic-ai/sdk"
const anthropic = billing.wrapAnthropic(new Anthropic(), { customerId: "cust_123" })
const response = await anthropic.messages.create({
model: "claude-sonnet-4-6",
max_tokens: 1024,
messages: [{ role: "user", content: "Hello" }],
})Gemini
import { GoogleGenerativeAI } from "@google/generative-ai"
const genAI = billing.wrapGemini(
new GoogleGenerativeAI(process.env.GEMINI_API_KEY!),
{ customerId: "cust_123" }
)
const model = genAI.getGenerativeModel({ model: "gemini-1.5-pro" })
const result = await model.generateContent("Hello")Wrapper options
billing.wrapOpenAI(client, {
customerId: "cust_123",
silentErrors: true, // default: true — billing failures never break LLM calls
onReport: (event) => {
console.log(`${event.provider} used ${event.totalTokens} tokens`)
},
})Reported usage types per call: tokens_input, tokens_output, tokens_total.
Error Handling
import { AtheraClient, BillingError } from "atehra-sdk"
try {
await billing.plans.get("nonexistent")
} catch (err) {
if (err instanceof BillingError) {
console.log(err.status) // HTTP status (404, 422, etc.)
console.log(err.code) // error code ("NOT_FOUND", "CONFLICT", etc.)
console.log(err.message) // human-readable message
}
}Environment Variables (recommended)
BILLING_API_KEY=bill_xxx
BILLING_BASE_URL=https://billing-api-production-409b.up.railway.app/v1const billing = new AtheraClient({
apiKey: process.env.BILLING_API_KEY!,
baseUrl: process.env.BILLING_BASE_URL!,
})