Hasapla Node.js SDK
的官方TypeScript SDK Hasapla这是人工智能公司的计费平台。
对Node.js 18及更新版本的客户余额、客户、组织、特性、计划、订阅和使用事件的类型访问。
安装
npm install hasapla
初始化
创建一个客户机,并在整个服务器应用程序中重用它。将API密钥保存在服务器上。
import { Hasapla } from "hasapla";
const hasapla = new Hasapla({
apiKey: process.env.HASAPLA_API_KEY!,
});
平衡
const balance = await hasapla.balance.get({
extCustomerId: "customer-123",
});
// { balance: 3000, unlimited: false }
只提供其中一个 extCustomerId 或 extOrganizationId. SDK将这些映射到API ext_customer_id 和 ext_organization_id 查询参数。无限订阅回报 { balance: null, unlimited: true };待定的有限订阅返回零。此端点不授权使用或刷新过期期限。
这将取代之前的占位符:结果现在是一个对象而不是一个数字,并且无限余额是 null 而不是 -1。
客户
await hasapla.customers.create({
email: "[email protected]",
name: "Example Customer",
extCustomerId: "customer-123",
});
订阅
为客户或组织订阅一个计划。只提供其中一个 customer_uuid 或 organization_uuid 间隔为 "month" 或 "year"。
const subscription = await hasapla.subscriptions.subscribe({
customer_uuid: "customer-uuid",
plan_uuid: "plan-uuid",
interval: "month",
});
免费计划立即激活。付费计划仍然悬而未决,没有期限日期和信用授予。间隔不会选择不同的目录价格。订阅字段使用API的snake_case名称。
查看客户当前的订阅:
const subscriptions = await hasapla.subscriptions.list({
customer_uuid: "customer-uuid",
current: true,
});
使用 organization_uuid 对于一个组织来说。结果是一个数组,它可以是空的。省略 current 包括历史订阅。分页接受 limit (1-1000,默认100)和 offset 0(默认)。
通过UUID检索订阅:
const subscription = await hasapla.subscriptions.get("subscription-uuid");
立即改变计划或间隔:
const replacement = await hasapla.subscriptions.change("subscription-uuid", {
plan_uuid: "target-plan-uuid",
interval: "month",
activate_immediately: true,
payment_reference_id: "verified-payment-reference",
amount: 3000,
currency: "USD",
});
对于付费目标,首先在服务器上验证付款,并提供完整的目标价格和货币。对于免费目标,省略所有三个支付字段。相同间隔的更改保留续订日期,除非从免费转为付费;间隔更改开始一个新的时间段。匹配重试将返回现有的后继程序,选择相同的计划和间隔不会进行任何更改。计划更改(activate_immediately: false)当前返回HTTP 409。
使用事件
await hasapla.events.create({
extCustomerId: "customer-123",
featureKey: "api_call",
});
在执行工作之前保留一个事件,然后在成功时捕获它,否则释放它:
const reservation = await hasapla.events.reserve({
extCustomerId: "customer-123",
featureKey: "api_call",
});
if (!reservation.key) {
throw new Error("Reservation key is missing");
}
try {
await performWork();
await hasapla.events.capture({ key: reservation.key });
} catch (error) {
await hasapla.events.release({ key: reservation.key });
throw error;
}
当客户用完功能限额时, reserve 抛出一个 409 可以检查的错误 isFeatureLimitReachedError:
import { isFeatureLimitReachedError } from "hasapla";
try {
await hasapla.events.reserve({
extCustomerId: "customer-123",
featureKey: "api_call",
});
} catch (error) {
if (isFeatureLimitReachedError(error)) {
console.error("Feature limit reached");
} else {
throw error;
}
}
错误
API响应失败抛出 HasaplaError 使用HTTP状态和解析后的响应体。
import { HasaplaError } from "hasapla";
try {
await hasapla.customers.get({ externalId: "missing-customer" });
} catch (error) {
if (error instanceof HasaplaError) {
console.error(error.status, error.body);
}
throw error;
}
许可证
apache - 2.0