SDK
StableOps API SDK
@stableops/api-sdk 安装、配置与调用。
安装
pnpm add @stableops/api-sdk默认 API Client 面向 Node 18+ 与提供全局 fetch、AbortController、
crypto.randomUUID 的 Edge Runtime。Webhook 验签与 Mock Server 是 Node.js 专用入口。
配置
import { StableOps } from '@stableops/api-sdk'
const client = new StableOps({
apiKey: process.env.STABLEOPS_API_KEY!,
organizationSlug: 'demo',
environment: 'sandbox',
// 可选。默认指向托管 API;自托管或 mock 测试时覆盖。
baseUrl: process.env.STABLEOPS_API_URL,
// 可选。注入自定义 fetch(msw、undici、edge fetch 等)。
fetch: globalThis.fetch,
})支付订单
const order = await client.paymentOrders.create(
{
merchantOrderId: 'sub_89231_2026_06',
amount: '49.00',
settlementAsset: 'USDC',
acceptedAssets: [
{ chain: 'base', asset: 'USDC' },
{ chain: 'tron', asset: 'USDT' },
],
// 30 分钟后未支付自动过期,订单进入 expired 并释放地址。
expiresAt: new Date(Date.now() + 30 * 60 * 1000).toISOString(),
},
{ idempotencyKey: crypto.randomUUID() },
)
await client.paymentOrders.retrieve(order.id)
await client.paymentOrders.list({ status: 'detected', limit: 50 })
await client.paymentOrders.cancel(order.id)paymentOrders.create 始终需要 idempotencyKey。建议用订单 id 派生的 UUID,
worker 重试时落到同一记录。
事件
const events = await client.events.list({
chain: 'base',
asset: 'USDC',
paymentOrderId: order.id,
})amount 是最小单位字符串,不要用 Number(amount)。
Webhook 端点
const endpoint = await client.webhookEndpoints.create({
url: 'https://your-app.example.com/hooks/stableops',
enabledEvents: ['payment.detected', 'payment.confirmed', 'payment.finalized'],
})
// endpoint.secret 只在这里出现一次,请妥善保存。
await client.webhookEndpoints.rotateSecret(endpoint.id)错误
所有非 2xx 都会抛 StableOpsError,带 .status / .code / .message / .details。
import { StableOpsError } from '@stableops/api-sdk'
try {
await client.paymentOrders.create(input, { idempotencyKey: key })
} catch (err) {
if (err instanceof StableOpsError && err.status === 409) {
// Idempotency-key 被相同 key 不同 body 复用
}
throw err
}本地 Mock 服务
SDK 自带一个进程内 Mock,适合契约测试与文档示例:
import { StableOps } from '@stableops/api-sdk'
import { MockServer } from '@stableops/api-sdk/mock'
import { verifySignature } from '@stableops/api-sdk/webhooks'
const mock = new MockServer()
const { url } = await mock.listen()
const client = new StableOps({ baseUrl: url, environment: 'sandbox' })
await client.paymentOrders.create(
{
/* … */
},
{ idempotencyKey: 'a' },
)
const fixture = mock.buildSignedFixture(endpoint.id, 'payment.detected', {
id: order.id,
})
verifySignature({
secret: fixture.secret,
header: fixture.header,
rawBody: fixture.rawBody,
})
await mock.close()Mock 只实现 SDK 契约测试所需的最小接口:payment orders、webhook endpoints、 以及签名 fixture 构造。