> ## Documentation Index
> Fetch the complete documentation index at: https://docs.clinkbill.com/llms.txt
> Use this file to discover all available pages before exploring further.

# TypeScript SDK

> Clink API 官方 Node.js 库。

Clink Node.js SDK 为服务端 JavaScript 和 TypeScript 应用提供了便捷的 Clink API 调用方式，并内置了完整的 TypeScript 类型定义。

<Card title="NPM Package" icon="npm" href="https://www.npmjs.com/package/@clink-ai/clink-typescript-sdk">
  在 npmjs.com 查看该包
</Card>

## 安装

使用你偏好的包管理器安装：

<CodeGroup>
  ```bash npm theme={null}
  npm install @clink-ai/clink-typescript-sdk
  ```

  ```bash yarn theme={null}
  yarn add @clink-ai/clink-typescript-sdk
  ```

  ```bash pnpm theme={null}
  pnpm add @clink-ai/clink-typescript-sdk
  ```
</CodeGroup>

## 快速开始

开始使用前，需要先用你的 API Key 初始化客户端。你可以在 Clink Dashboard 的 **Developers** 页面找到密钥。

<Warning>
  **安全提示：** 该 SDK 仅适用于服务端。不要在浏览器端代码或公开仓库中暴露 **Secret API keys**。
</Warning>

```typescript theme={null}
import { ClinkPayClient } from '@clink-ai/clink-typescript-sdk';

const client = new ClinkPayClient({
  apiKey: 'YOUR_API_KEY',
  env: 'sandbox',
});

async function main() {
  const session = await client.createCheckoutSession({
    originalAmount: 1999,
    originalCurrency: 'USD',
    uiMode: 'hostedPage',
    successUrl: 'https://merchant.example.com/success',
    cancelUrl: 'https://merchant.example.com/cancel',
    allowPromotionCodes: true,
  });

  console.log(session.sessionId);
  console.log(session.url);
}

main();
```

如果你要创建嵌入式 checkout session，请将 `uiMode` 设置为 `elements`，并提供 `returnUrl`，例如 `https://YOUR_DOMAIN/complete.html?session_id={ELEMENTS_SESSION_ID}`。Clink 会将 `{ELEMENTS_SESSION_ID}` 替换为创建出的 session ID。

## API 概览

* `createCheckoutSession(options)`：创建 checkout session，并返回跳转 `url`
* `getCheckoutSession(sessionId)`：查询 checkout session 详情
* `getOrder(orderId)`：查询订单详情
* `getRefund(refundId)`：查询退款详情
* `getSubscription(subscriptionId)`：查询订阅详情
* `getInvoice(invoiceId)`：查询订阅发票详情
* `customerPortalSession(options)`：创建 customer portal session，并返回访问链接

所有方法都是异步的，接口返回错误时会抛出异常。

## 错误处理

当 API 返回非成功状态码（4xx 或 5xx）时，SDK 会抛出错误。建议用 `try/catch` 包裹调用逻辑。

```typescript theme={null}
import { ClinkPayClient } from '@clink-ai/clink-typescript-sdk';

const client = new ClinkPayClient({ apiKey: 'YOUR_API_KEY', env: 'sandbox' });

async function demo() {
  try {
    const order = await client.getOrder('ord_123');
    console.log(order.status);
  } catch (e) {
    if (e instanceof ClinkApiError) {
      const { code, message } = e;
      // your code here
    }
    // handle other errors
  }
}

demo();
```

## 参考资料

* [API 详细示例](https://www.npmjs.com/package/@clink-ai/clink-typescript-sdk?activeTab=readme)
