> ## 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

> The official Node.js library for the Clink API.

The Clink Node.js SDK provides convenient access to the Clink API from applications written in server-side JavaScript or TypeScript. It includes TypeScript definitions for all request parameters and response fields.

> [card] [NPM Package](https://www.npmjs.com/package/@clink-ai/clink-typescript-sdk)
>
> View the package on npmjs.com

## Installation

Install the package with your preferred package manager:

```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
```

## Quick Start

To start using the SDK, you need to initialize the client with your API Key. You can find your secret keys in the **Developers** section of your Clink dashboard.

> [!WARNING]
>
> **Security Note:** The SDK is intended for server-side use only. Never expose your **Secret API keys** in client-side code (browsers) or public repositories.

```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({
    customerEmail: 'customer@example.com',
    originalAmount: 19.99,
    originalCurrency: 'USD',
    uiMode: 'hostedPage',
    priceDataList: [
      { name: 'Test item', quantity: 1, unitAmount: 19.99, currency: 'USD' },
    ],
    successUrl: 'https://merchant.example.com/success',
    cancelUrl: 'https://merchant.example.com/cancel',
    allowPromotionCodes: true,
  });

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

main();
```

For [Elements](https://docs.clinkbill.com/elements.md), create the session with `uiMode: 'elements'` and provide `returnUrl`, for example `https://YOUR_DOMAIN/complete.html?session_id={ELEMENTS_SESSION_ID}`. Clink replaces `{ELEMENTS_SESSION_ID}` with the created session ID.

For the embedded iframe from [`@clink-ai/clink-js`](https://docs.clinkbill.com/api-reference/javascript_sdk), use `uiMode: 'hostedPage'` instead — that SDK mounts the hosted checkout page as-is.

## API Overview

* `createCheckoutSession(options)`: Create a checkout session and get the redirect `url`.
* `getCheckoutSession(sessionId)`: Retrieve checkout session details.
* `getOrder(orderId)`: Retrieve order details.
* `getRefund(refundId)`: Retrieve refund details.
* `getSubscription(subscriptionId)`: Retrieve subscription details.
* `getInvoice(invoiceId)`: Retrieve subscription invoice details.
* `customerPortalSession(options)`: Create a customer portal session and get the access link.

All methods are asynchronous and throw on errors.

## Error Handling

When the API returns a non-success status code (4xx or 5xx), the SDK throws an error. You should wrap your API calls in `try/catch` blocks.

```typescript theme={null}
import { ClinkPayClient, ClinkApiError } 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('order_123');
    console.log(order.status);
  } catch (e) {
    if (e instanceof ClinkApiError) {
      const { code, message } = e;
      // your code here
    }
    // handle other errors
  }
}

demo();
```

## Verifying webhooks

`ClinkWebhook` computes and compares the HMAC for you, so you do not have to write it yourself.

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

const webhook = new ClinkWebhook({ signatureKey: process.env.CLINK_WEBHOOK_SIGNING_KEY });

const REPLAY_WINDOW_MS = 5 * 60 * 1000;

// The SDK checks the HMAC only — screen these two before calling it
if (headers['x-clink-signtype'] !== 'SHA256') return reject401();

const ts = Number(headers['x-clink-timestamp']);
if (!Number.isFinite(ts) || Math.abs(Date.now() - ts) > REPLAY_WINDOW_MS) return reject401();

try {
  const event = webhook.verifyAndGet({
    timestamp: headers['x-clink-timestamp'],
    body: rawBody,              // the raw body, before JSON parsing
    headerSignature: headers['x-clink-signature'],
  });

  // event.id, event.type, event.data.object
} catch (e) {
  if (e instanceof ClinkWebhookSignatureError) {
    // reject with 401
  }
}
```

> [!WARNING]
>
> **`verifyAndGet()` in `1.0.1` verifies the HMAC and nothing else.** It does not check `X-Clink-SignType`, does not check timestamp freshness, and compares signatures with `===` rather than a constant-time comparison.
>
> The first two are screened above. For the third, compute the HMAC yourself with `crypto.timingSafeEqual` — see [Hosted Checkout](https://docs.clinkbill.com/build-integration.md).
>
> Verifying the signature is also not the same as being safe to act on. Deduplicate on `event.id` with a unique index before doing any work.

`verifySignature()` returns a boolean instead of throwing, and `signature()` generates one — useful for building signed test events locally.

## References

* [Detailed Example for APIs](https://www.npmjs.com/package/@clink-ai/clink-typescript-sdk?activeTab=readme)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.