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

# Agent Elements SDK

> Embed Clink card management in a host app: the server issues element credentials, the browser mounts a Clink-hosted iframe.

`@clink-ai/agent-elements` embeds Clink's wallet card UI inside a host application. The host server issues credentials per element type, and the frontend creates one element and mounts it into a container. Card forms, card data, and 3DS all live in the Clink-hosted iframe, so the host page never handles card data.

> [!NOTE]
>
> Pin the `@clink-ai/agent-elements` version in production. For every option and method, see the [SDK reference](https://docs.clinkbill.com/guides/agent/agent_elements/api_reference.md).

## The full chain

Agent Elements replaces only the frontend card UI. **Credentials must still be issued by your server**, because obtaining them requires the client secret Clink assigned to you.

```mermaid theme={null}
sequenceDiagram
  participant B as Host frontend
  participant M as Host backend
  participant C as Clink platform (API / BFF)
  participant E as Agent Elements iframe

  B->>M: 1. Request element credentials (paymentMethods or vault)
  M->>C: 2. Exchange client secret for a portal token
  M->>C: 3. Create a card-session or vault-session
  C-->>M: 4. Return a card-session token / vaultId
  M-->>B: 5. Return only that element's credential
  B->>E: 6. createElement + mount
  E->>C: 7. Load card data (vault exchanges vaultId first)
  E-->>B: 8. initialized / card-added / completed
  B->>M: 9. Continue your flow with paymentInstrumentId
```

Never send the client secret or portal token from step 2 to the browser. The frontend receives exactly one of two things: a card-session token for `paymentMethods`, or a vaultId for `vault`.

### Who owns what

| Party | Owns | Must not do |
| - | - | - |
| Host frontend | Construct the instance and element, mount the iframe, update its own UI from events | Hold the client secret or portal token, put credentials in the iframe URL |
| Host backend | Exchange and store platform credentials, issue element credentials, map cards to local users | Forward the client secret or portal token to the browser |
| Clink platform | Validate credentials, issue card-session tokens and vaultIds, render the card UI | Create host orders or charge cards |
| Clink-hosted iframe | Load card data, handle card actions, unlocking and 3DS, emit events | Store host business state or touch host backend credentials |

## 1. Server: issue element credentials

The two elements get their credentials from different endpoints, both behind the same platform auth.

### 1.1 Client token and portal token

A client token comes from `client_credentials`; a portal token is then scoped to a user email.

```javascript theme={null}
const API = 'https://uat-api.clinkbill.com'; // sandbox (UAT), see "Environments"

// client token
const client = await postForm(`${API}/agent/cwallet/oauth/token`, {
  grant_type: 'client_credentials',
  client_id: CLIENT_ID,
  client_secret: CLIENT_SECRET,
});

// portal token for an authorized user email
const portal = await postJson(
  `${API}/agent/cwallet/platform/portal/tokens`,
  { email: user.email },
  client.access_token,
);
```

* `client_id` / `client_secret` are assigned by Clink and stay on the server.
* Portal tokens accept `email` only, **not `customer_id`**.
* The email must already be authorized for the client. Otherwise the call returns `71211003 The redirect URI is not registered for this client`.
* Both the client token and the portal token live for 3600s.

### 1.2 paymentMethods: create a card-session

```javascript theme={null}
const session = await postJson(
  `${API}/agent/platform/card-sessions`,
  {},
  portal.access_token,
);

res.json({ token: session.access_token });
```

The returned `access_token` (scope `card:manage`) is the `paymentMethods` credential and lives for 1799s. It only reaches the current user's card endpoints, so it can be sent to the browser.

### 1.3 vault: create a vault session

```javascript theme={null}
const vault = await postJson(
  `${API}/agent/platform/vault-sessions`,
  {},
  portal.access_token,
);

res.json({ vaultId: vault.vault_id });
```

```json theme={null}
{
  "vault_id": "vs_xxxxxxxx",
  "url": "https://uat-agent.clinkbill.com/vault/vs_xxxxxxxx",
  "expires_at": "2026-11-16T08:30:15.649Z"
}
```

* Send `vault_id` to the `vault` element. It is valid for about 30 minutes.
* `url` is the passwordless card-binding page for direct browser use; SDK integrations do not use it.
* The iframe exchanges `vaultId` for a vault token (about 899s); the host never sees that token.

> [!WARNING]
>
> Keep the client secret, client token, and portal token on the server. Your wrapper endpoint should return only `{ token }` or `{ vaultId }`.

## 2. Frontend: initialize and mount

### Environments

`environment` decides which Clink app the iframe loads, and which API your server calls.

| `environment` | Iframe app origin | Server API |
| :- | :- | :- |
| `sandbox` | `https://uat-agent-elements.clinkbill.com` | `https://uat-api.clinkbill.com` |
| `production` | `https://agent-elements.clinkbill.com` | Provided by Clink |

`environment` is required: use `sandbox` (UAT) while integrating and `production` after go-live. Never mix credentials across environments; mixing returns 401. The app origin comes from `environment` only; the SDK accepts no runtime override.

### Install

```bash theme={null}
npm install @clink-ai/agent-elements
```

The package ships ESM and an IIFE build; see [Package formats](https://docs.clinkbill.com/guides/agent/agent_elements/api_reference.md#package-formats).

### Create the instance

```ts theme={null}
import { AgentElements } from '@clink-ai/agent-elements';

const instance = new AgentElements({
  environment: 'sandbox',
  presetOptions: { locale: 'en-US' },
});
```

One `AgentElements` instance creates one element. Create two instances to use both elements.

### Create the element

The element type decides the credential and the available mount options. Credentials are passed to `createElement`, are required, and cannot be empty.

```ts theme={null}
// paymentMethods: a card-session token issued by your server
const cardManager = instance.createElement('paymentMethods', { token });

// vault: a one-time vaultId issued by your server
const vaultElement = new AgentElements({ environment: 'sandbox' }).createElement(
  'vault',
  { vaultId },
);
```

| Element | What the user can do | Credential |
| :- | :- | :- |
| `paymentMethods` | View saved cards, add a card, set the default card, delete a card | card-session token (1799s) |
| `vault` | Select a saved card and unlock it with its CVV, or add a card | vaultId (one-time, about 30 minutes) |

### Mount

```ts theme={null}
element.mount('#clink-card-management', {
  hideExistingCards: false,
  hideDelete: false,
  hideSetDefault: false,
  button: { height: 48 },
});
```

The container can be a CSS selector or an `HTMLElement` and needs a stable width. The SDK sets the height and it grows with the content, so do not fix it. The host must run in a current browser with iframe and `postMessage` support.

Mount options apply to the next mount only. Unmount and mount again to change them.

| Element | Option | Effect |
| :- | :- | :- |
| Both | `hideSkeleton` | Hide the loading skeleton |
| Both | `button` | Primary action button appearance: `height` / `fontSize` / `radius`, in px |
| `paymentMethods` | `hideExistingCards` | Hide the saved-card list |
| `paymentMethods` | `hideDelete` | Hide the delete action |
| `paymentMethods` | `hideSetDefault` | Hide the set-default action |
| `vault` | `hideHeader` | Hide the title and subtitle |

Mount options are presentation only and are encoded into the iframe URL. **Never put tokens or other secrets in them.**

## 3. Events and state sync

Events are scoped to the element and subscribed with `element.on` / `element.off`. Register listeners before `mount()` so none are missed.

| Event | Element | Payload | Fired when |
| :- | :- | :- | :- |
| `initialized` | Both | None | Card data loads for the first time; once per page load |
| `card-added` | Both | `{ paymentInstrumentId }` | A card is added, including after 3DS |
| `card-deleted` | `paymentMethods` | `{ paymentInstrumentId }` | A card is deleted |
| `default-changed` | `paymentMethods` | `{ paymentInstrumentId }` | A card becomes the default |
| `completed` | `vault` | `{ paymentInstrumentId }` | A saved card is unlocked, including after 3DS |
| `token-expired` | Both | None | The API returns 401; at most once per token cycle |
| `error` | Both | `{ message, source }` | A load, card action, add-card, or 3DS step fails |

```ts theme={null}
element.on('card-added', ({ paymentInstrumentId }) => {
  // Sync your card list.
});
element.on('completed', ({ paymentInstrumentId }) => {
  // vault: use the unlocked card in your flow.
});
element.on('error', ({ message, source }) => {
  console.error(source, message);
});
```

`error.source` is one of:

| Source | Meaning |
| :- | :- |
| `session` | A card-data load or session-level failure |
| `runtime` | An unexpected runtime error |
| `payment` | The card or payment operation failed |

### Token expiry

On `token-expired`, `paymentMethods` fetches a new card-session token from your backend and calls `setToken`:

```ts theme={null}
element.on('token-expired', async () => {
  element.setToken(await fetchCardSessionToken());
});
```

The iframe reloads its card data after the new token arrives and resets the once-per-cycle counter. Calling `setToken` before `mount` only updates the in-memory value, which is sent with the next `init`.

`vault` has no refreshable token: when the session expires, request a new `vaultId` and rebuild the element.

### Clean up

```ts theme={null}
instance.destroy();
```

`destroy()` removes the iframe, closes any open 3DS overlay, and clears the element's listeners. The instance cannot be reused. `unmount()` only removes the iframe and wrapper; subscriptions survive and the element can be mounted again.

## 4. Appearance

Appearance is set when the instance is created:

```ts theme={null}
const instance = new AgentElements({
  environment: 'sandbox',
  presetOptions: {
    locale: 'en-US',
    primaryColor: '#1677ff',
    radius: { components: 8, card: 8 },
  },
});
```

| Option | Default | Effect |
| :- | :- | :- |
| `locale` | `en-US` | UI language and antd locale; `en-US` or `zh-CN` |
| `primaryColor` | `#1677ff` | Component primary color |
| `radius.components` | `8` | Component corner radius, in px |
| `radius.card` | `8` | Card container radius, in px |

Options are applied when the SDK sends `init`. `setLocale` updates the language at runtime; the other options cannot change after construction.

## 5. Limits

* One element per `AgentElements` instance. Create two instances to mount `paymentMethods` and `vault` together.
* The card UI cannot be restyled beyond the preset options; there is no custom CSS hook.
* 3DS runs in an iframe overlay only; popup and full-page redirect modes are not supported.
* The host server owns `token` / `vaultId` acquisition and refresh.


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