Skip to content

withBilling 工具函数

withBilling 是独立导出的高阶函数,将任意异步操作包装为「校验 → 执行 → 扣费」的完整流程。

函数签名

typescript
async function withBilling<T>(
  billing: BillingModule,           // sdk.billing
  action: () => Promise<T>,         // 要执行的异步操作
  options?: BillingConsumeOptions,  // consume 参数(可选)
): Promise<WithBillingResult<T>>    // { result: T, billing: BillingConsumeResult }

执行流程

1. billing.check() — 积分不足时直接 reject SdkError(40301)
2. action() — 执行实际操作(如 download / openInStudio)
3. billing.consume() — 操作成功后扣费
   - 免费时段内跳过扣费,直接返回缓存结果
   - 若 `billing.consume()` 返回 `isBlacklisted=true`,表示用户命中黑名单(后端 `20102`)

使用示例

ESM 方式

typescript
import { GeneratorSDK, withBilling } from '@atomm-developer/generator-sdk'

const sdk = GeneratorSDK.init({ appKey: 'app_xxx' })

// 带计费的下载
try {
  const { result, billing } = await withBilling(
    sdk.billing,
    () => sdk.export.download({ fileName: 'my-design.png' }),
  )
  console.log('下载成功:', result.fileName)
  console.log('剩余免费:', billing.freeRemaining)
} catch (err) {
  if (err.code === 40301) alert('积分不足,请充值')
}

// 带计费的打开 Studio
await withBilling(
  sdk.billing,
  () => sdk.export.openInStudio(),
)

// 带计费的自定义操作
await withBilling(
  sdk.billing,
  () => myCustomAiGenerate(),
  { externalId: 'ai_gen_123' },
)

CDN 方式

javascript
const withBilling = GeneratorSDK.withBilling

document.getElementById('downloadBtn').onclick = async () => {
  try {
    await withBilling(sdk.billing, () =>
      sdk.export.download({ fileName: 'my-design.png' }),
    )
  } catch (err) {
    if (err.code === 40301) alert('积分不足,请充值')
  }
}

MIT Licensed