# @alguna/sdk 中文文档

规范地址：https://npmcn.com/package/%40alguna/sdk/

版本：0\.4\.0
npm 元数据更新时间：2026-10-19T12:13:04.212Z
中文译文更新时间：2026-11-05T21:21:18.914Z
软件包许可：Apache-2\.0

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40alguna/sdk
原文对照：https://npmcn.com/package/%40alguna/sdk/?lang=original
项目主页：https://alguna.com/docs
源码仓库：https://github.com/alguna-io/alguna-ts

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：5.2 MB，9 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=20\.0\.0
- 运行依赖：0 个
- 首次发布：2026-08-11T08:40:46.827Z
- 最新版本发布：2026-10-19T12:13:03.930Z
- 近 30 天下载量：19262（2026-10-06 至 2026-11-04，npm 官方下载统计）
- 已发布版本数：4（近 12 个月 4 个）

## 中文简介

Alguna 公共 API 的官方类型脚本 SDK

## 安装

```sh
npm install @alguna/sdk
```

也可以使用：`pnpm add @alguna/sdk`、`yarn add @alguna/sdk`、`bun add @alguna/sdk`

## README

# @alguna/ sdk (英语)

官方类型SDK [阿尔古纳 API](https://alguna.com/docs): 基于用法 账单、订阅、发票和付款。 从0.3升级? 读取 [误入歧途](https://github.com/alguna-io/alguna-ts/blob/main/MIGRATING.md)。 。 。 .

## 安装

```bash
npm install @alguna/sdk
```

SDK需要20或以后的节点.js, 或者另一个与全局运行的时间 `fetch` 财务报告和审定财务报表 `crypto.randomUUID()`比如德诺、邦克或克洛德弗莱尔工人 仅在服务器上使用: API 密钥是一个秘密 .

## 客户端

在仪表板下创建 API 密钥 **设置 – 连接 – 开发者 – API 密钥**。 。 。 . 钥匙看起来像 `<key_id>.<key_secret>`。 。 。 .

```typescript
import { Alguna } from "@alguna/sdk";

// With no options, the client reads the key from ALGUNA_API_KEY.
const alguna = new Alguna();

const sandbox = new Alguna({
  apiKey: process.env.ALGUNA_SANDBOX_API_KEY, // a string, or a function called on every request
  apiVersion: "2026-04-01", // default: the version this SDK release targets
  baseUrl: "https://api.sandbox.alguna.io", // default: https://api.alguna.io
  headers: { "X-Trace-Id": "abc" }, // sent on every request
  fetch: globalThis.fetch, // your own fetch, for example to add tracing
  logging: { level: "debug", silent: false }, // silent by default
});
```

`new Alguna()` 丢出一个 `AlgunaError` 当它找不到钥匙时:没有 `process.env` (工人,德诺),通过 `apiKey`笔 `apiVersion` 保持您的整合 当您升级软件包时, 一个 API 版本 。 SDK发送 `User-Agent: alguna-ts/<version>` 在运行时间允许的情况下( 不在浏览器中); a `User-Agent` 内 `headers` 替换它. `console.log(alguna)` 财务报告和审定财务报表 `JSON.stringify(alguna)` 从不打印 API 密钥.

## 请求

客户端每个 API 资源有一个字段(`alguna.customers`, (中文(简体) ), `alguna.subscriptions`, (中文(简体) ), `alguna.invoices`, (中文(简体) ), `alguna.wallets`)和每次操作的一种方法。 请求和 响应类型从软件包根导出(`CreateCustomerRequest`, (中文(简体) ), `InvoiceResponse`)和在 `AlgunaApi` 名称空间.

```typescript
import { Alguna } from "@alguna/sdk";

const alguna = new Alguna();

const customer = await alguna.customers.create({
  name: "Acme Corp",
  currency: "USD",
  contacts: [{ email: "billing@acme.com", is_primary: true }],
});

const invoice = await alguna.invoices.create({
  customer_id: customer.id,
  currency: "USD",
  line_items: [{ description: "Onboarding", unit_price: "500.00", quantity: "1" }],
});

// A hosted customer portal session, where the customer can pay. It is valid for 1 hour.
const session = await alguna.portal.createSession({ customer_id: customer.id });
console.log(invoice.id, session.url);
```

每一种方法都以每个请求选项作为其最后的论点: `idempotencyKey` (写作), `timeoutInSeconds`, (中文(简体) ), `maxRetries`, (中文(简体) ), `headers` 财务报告和审定财务报表 `abortSignal`。 。 。 . `invoices.generatePdf`, (中文(简体) ), `quotes.getPdf` 财务报告和审定财务报表 `subscriptions.downloadPdf` 返回 a `BinaryResponse`: 读取用 `arrayBuffer()`, (中文(简体) ), `blob()` 或者说 `stream()`。 。 。 .

对于SDK尚未覆盖的终点, `alguna.fetch(path, init, options)` 发送原始 请使用客户端的认证、信头、超时、“同上”键和重试。 它回来了 平原地区 `Response`不论地位如何 当你通过 `init`、方法、标题和正文 来自 `init` 只是,不是从一个 `Request` 你通过作为 `path`. 溪流体,例如: 机构名称 `Request`,在第一次尝试之前读入内存,以便重试可以发送 又来了.

## 倾斜

列表方法返回 a `Page`数字 : `data` 持有当前页面的项目,以及 `response` 整个身体,与 `pagination`。 。 。 .

```typescript
import { Alguna } from "@alguna/sdk";

const alguna = new Alguna();

const page = await alguna.customers.list({ limit: 50 });
console.log(page.data.length, page.response.pagination); // { per_page, total_pages }

// The SDK gets the next page when you need it.
for await (const customer of await alguna.customers.list({ limit: 100 })) {
  console.log(customer.id);
}
```

API发送最多操作 `limit` 最大每页(今天每个列表100个). 第一页的重复停止,项目少于 `limit`,或当 `limit` 规模更大。 当最后一页完全满后, SDK 还会再提出一个请求 返回空页。 手接一页,使用 `page.hasNextPage()` 财务报告和审定财务报表 `page.getNextPage()`。 。 。 .

## 失职和重审

每一个请求,如果不是一个GET 发送 `Idempotency-Key`: 专辑 `idempotencyKey`,或一个 UUID v4是SDK为呼叫而作. 每次重试都发出相同的键,所以 API 返回第一个结果, 并且不再写 。 自己把钥匙交出来 重复给自己打电话, 例如在重启后:

```typescript
import { Alguna } from "@alguna/sdk";

const alguna = new Alguna();

await alguna.customers.create(
  { name: "Acme Corp", currency: "USD" },
  { idempotencyKey: "signup-1234" },
);
```

例外情况是 `events.ingest`, (中文(简体) ), `credits.track` 财务报告和审定财务报表 `credits.check`: 它们没有自动 键,因为API通过请求机构来识别他们的工作. 它可以删除重复的事件 `unique_id`, (中文(简体) ), 财务报告和审定财务报表 `credits.track` 同一人的功劳 `unique_id`s. 每一次呼叫都有新的钥匙 将身份替换为 `credits.track`,所以一个电话再次发出,例如通过排队,会 抽两次功劳 SDK在没有钥匙的情况下重复这些通话. 您通过的一个密钥被发送到 每一个尝试. `credits.check` 与 `reserve` 需要您的密钥, 因为密钥识别 别动.

失败的尝试默认要重审两次( 总共3次) :

-   状态为 `408`, (中文(简体) ), `429`, (中文(简体) ), `502`, (中文(简体) ), `503` 或者说 `504`· ;
-   状态为 `409` 带有 `Retry-After` 头曰. API 仅在请求时发送此选项 相同的密钥仍在运行。 A 类 `409` 无 `Retry-After` 真正的冲突 未再审;
-   未收到任何回复:连接被拒绝、重新设置或关闭,或尝试超时. 工人、 Deno 和浏览器没有说明为什么连接失败, 所以有 TLS 错误 复试也. 这很安全:每个经重审的请求都是GET,带有"同上"的Key,或者是 以上例外情况之一.

SDK 在您中断呼叫后不重试 `abortSignal`在尝试之间 等待 1 s, 然后是 2 s, 随机的焦点为 10% 。 当反应有 `Retry-After` (秒或一个HTTP日期),它等待了那么长时间,最多60 s. 设定 `maxRetries` 编辑 客户端或一通电话; `0` 关闭复试.

## 超时

60 s. s. set 之后的每次尝试时间 `timeout` (以毫秒计) `timeoutInSeconds` 一个电话。 计时尝试被重审,所以一个电话可以接 3×超时加等. 为了限制整个通话 通过一个 `abortSignal`: 当 中止, SDK 丢弃 `AbortError`。 。 。 .

```typescript
import { Alguna } from "@alguna/sdk";

const alguna = new Alguna({ timeout: 10_000 });

// Each attempt may take 5 s; the call, with its retries, at most 20 s.
const customer = await alguna.customers.get("cus_123", {
  timeoutInSeconds: 5,
  abortSignal: AbortSignal.timeout(20_000),
});
console.log(customer.name);
```

## 错误

SDK 抛出的每一个错误 `AlgunaError`数字 :

```typescript
import { Alguna, AlgunaError, NotFoundError, RateLimitError } from "@alguna/sdk";

const alguna = new Alguna();

try {
  await alguna.customers.get("nope");
} catch (error) {
  if (error instanceof NotFoundError) {
    console.log(error.message, error.statusCode, error.requestId);
  } else if (error instanceof RateLimitError) {
    console.log("retry in", error.headers["retry-after"], "seconds");
  } else if (error instanceof AlgunaError) {
    console.log(error.cause); // the underlying error, when there is one
  } else {
    throw error;
  }
}
```

| 错误 | 何时 |
| --- | --- |
| `ValidationError` | 400个 |
| `AuthenticationError` | 401 (中文(简体) ) |
| `PermissionDeniedError` | 403 (韩语) |
| `NotFoundError` | 404 (韩语) |
| `ConflictError` | 409个 |
| `UnprocessableEntityError` | 422(另见a/c.5/56/l.48) `ValidationError`(中文(简体) ) |
| `RateLimitError` | 429个 |
| `InternalServerError` | 5 (简体中文) |
| `ApiError` | 任何其他未成功状态 |
| `ConnectionError` | 无响应: DNS, TLS, 重置连接 |
| `TimeoutError` | `timeout` 超过(另加a) `ConnectionError`(中文(简体) ) |
| `AbortError` | 已终止 `abortSignal` |

答复错误 `message`, (中文(简体) ), `statusCode`, (中文(简体) ), `requestId`, (中文(简体) ), `code` (当身体有 一个, `body` 财务报告和审定财务报表 `headers` (小写). `message` 是尸体的吗 `detail`,否则 `title`, (中文(简体) ), 其它类型 `message`,否则 HTTP 状态文本。 连接失败没有 `statusCode`; 其编号 `cause` 保存原始错误。 给我 `requestId` 当您联系到支援时.

## 网络呼号

`AlgunaWebhookEvent` 是每个网友组成的联盟 收缩 `type` 键入 `data`数字 :

```typescript
import type { AlgunaWebhookEvent } from "@alguna/sdk";

function handle(event: AlgunaWebhookEvent) {
  switch (event.type) {
    case "payment.created":
      console.log(event.data.amount); // a decimal string
      break;
    default:
      break; // new event types can arrive before you upgrade
  }
}
```

SDK类型为有效载荷;它不检查Alguna是否发送了有效载荷. 阿尔古纳签下每批货 与斯维克丝. 在你相信有效载荷之前 验证一下它 `svix-id`, (中文(简体) ), `svix-timestamp` 财务报告和审定财务报表 `svix-signature` 与 Svix 库相对的原始请求正文 : `new Webhook(secret).verify(rawBody, headers)`。见 [验证签名](https://alguna.com/docs/api-reference/v2/webhooks#verifying-signatures)。 。 。 .

## 参考文献

-   [脚本 SDK 指南](https://alguna.com/docs/api-reference/v2/sdks/typescript)
-   [API 参考](https://alguna.com/docs/api-reference/v2/overview)
-   [错误](https://alguna.com/docs/api-reference/v2/errors) 财务报告和审定财务报表 [一能性](https://alguna.com/docs/api-reference/v2/idempotency)
-   支助: [支持@alguna.io](mailto:support@alguna.io),与 `requestId` 失败的呼叫

## 关于这个雷波

Alguna从一个私人寄存器中的Alguna API spec生成这个SDK. 二. 未决问题 在这里。 Alguna 端口代码更改生成器,所以此处的拉出请求不会像现在这样合并.

## 常见问题

### @alguna/sdk 是什么？

Alguna 公共 API 的官方类型脚本 SDK

### 如何安装 @alguna/sdk？

在项目目录运行 npm install @alguna/sdk，或使用 pnpm add / yarn add / bun add。

### @alguna/sdk 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @alguna/sdk 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @alguna/sdk 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=20\.0\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @alguna/sdk 可以商用吗？

@alguna/sdk 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @alguna/sdk 的下载量有多少？

根据 npm 官方下载统计，@alguna/sdk 在 2026/10/06 – 2026/11/04 这 30 天内被下载 19,262 次，日均约 642 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @alguna/sdk 还在维护吗？

最新版本 0\.4\.0 发布于 2026/10/19（19 天前）；至今共发布 4 个版本，其中过去 12 个月发布了 4 个；首次发布于 2026/08/11。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

