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

# Elements

> Embed Clink payment inputs in a merchant-owned checkout page, with the server still creating the Session.

Elements embeds the payment inputs, wallet buttons, 3DS, QR codes, and third-party payment interactions that Clink manages into a merchant-owned page. The order summary, page structure, pay button, and status messages stay with the merchant.

Use [Hosted Checkout](https://docs.clinkbill.com/build-integration.md) to get money moving fastest. Reach for Elements when the order summary, page structure, and interaction design have to be custom.

> [!NOTE]
>
> We recommend pinning the `@clink-ai/clink-elements` version.

## What the full chain looks like

Elements only replaces the frontend segment. **Creating the Session still has to happen on the merchant server**, because that call uses the Secret Key.

```mermaid theme={null}
sequenceDiagram
    participant B as Browser
    participant M as Merchant backend
    participant C as Clink API
    participant E as Clink Elements
    participant W as Merchant webhook

    B->>M: 1. Submit product ID or cart
    M->>M: 2. Validate items and amount, create pending local order
    M->>C: 3. Call POST /checkout/session with the Secret Key
    C-->>M: 4. Return sessionId, url, expireTime and more
    M->>M: Store local order - merchantReferenceId - sessionId mapping
    M-->>B: 5. Return only sessionId
    B->>E: 6. Initialize with sessionId and Publishable Key
    E->>E: 7. Render methods, handle submit, wallets, 3DS, QR codes
    C->>W: 8. Deliver payment events
    W->>M: Verify, deduplicate, update the local order
    B->>M: 9. Query merchant order status
    M-->>B: Return the final result
```

Step 1 submits a **product identifier**, not a final amount computed in the browser. The amount is recalculated server-side in step 2.

### Who owns what

| Party | Owns | Must not |
| - | - | - |
| Merchant frontend | Calling the merchant wrapper endpoint, initializing and mounting Elements, updating UI from SDK events, querying merchant order status | Hold the Secret Key, call Clink's Create Session directly, or decide on its own that a payment succeeded |
| Merchant backend | Validating items and amounts, creating the local order, calling Clink, storing the ID mapping, returning a frontend-safe payload, handling webhooks | Pass the Secret Key or Clink's full raw response to the browser |
| Clink API / Elements | Creating the Session, rendering secure payment UI, handling submission, third-party buttons, 3DS, and QR codes | Own the local order or the fulfillment |
| Clink webhook | Delivering server-side payment state to the merchant backend | Be replaced by frontend events |

## 1. Server: write a wrapper Session endpoint

This layer is not an optional optimization. It is three boundaries at once: **the Secret Key security boundary, the amount validation boundary, and the local order association boundary.**

The `clinkRequest` helper below is the authenticated helper from [Hosted Checkout](https://docs.clinkbill.com/build-integration.md); it returns the `data` field of the response.

```javascript theme={null}
// This is the merchant backend endpoint, not a Clink browser API
app.post('/api/payments/elements-session', requireUser, async (req, res) => {
  const { productId, quantity } = req.body;

  // Recalculate server-side; never trust a price from the browser
  const quote = await catalog.quote(productId, quantity);

  const order = await orders.createPending({
    customerId: req.user.id,
    amount: quote.amount,
    currency: quote.currency,
  });

  const session = await clinkRequest('/checkout/session', {
    customerEmail: req.user.email,
    merchantReferenceId: order.id,
    originalAmount: quote.amount,
    originalCurrency: quote.currency,
    priceDataList: quote.items,
    uiMode: 'elements',
    returnUrl: `${APP_ORIGIN}/payment/return?session_id={ELEMENTS_SESSION_ID}`,
  });

  await orders.bindSession(order.id, session.sessionId);

  // This is a custom frontend response — keep it minimal
  res.json({ sessionId: session.sessionId });
});
```

Three things to get right:

* `uiMode` is `elements` and `returnUrl` is required. Put `{ELEMENTS_SESSION_ID}` in the URL and Clink substitutes the real Session ID
* The field is `returnUrl`. Older material calls it `redirectUrl`, which is wrong — `redirectUrl` is a response field used in `requires_action` flows
* `merchantReferenceId` is for reconciliation only. It is **not an idempotency key**; the same value twice produces two Sessions

### What Clink returns

The `data` that `clinkRequest` hands back looks like this:

```json theme={null}
{
  "sessionId": "sess_xxxxxxxx",
  "uiMode": "elements",
  "returnUrl": "https://merchant.example.com/payment/return?session_id=sess_xxxxxxxx",
  "url": "https://uat-checkout.clinkbill.com/...",
  "merchantReferenceId": "merchant_order_xxx",
  "expireTime": "2026-07-30 12:00:00"
}
```

Clink's raw response wraps this in a `{ "code": 200, "msg": "success", "data": { ... } }` envelope; `clinkRequest` has already unwrapped it.

> [!NOTE]
>
> `expireTime` currently comes back as `"2026-07-30 12:00:00"` — **no timezone designator**, and not RFC 3339.
>
> Do not hand it straight to `new Date()` or parse it as local time; different runtimes will disagree.
>
> **Do not infer a "merchant account timezone" or the browser timezone either.** The backend currently serializes using the service process default timezone, with no per-account conversion, so the string does not state which zone it belongs to.
>
> Precise cross-timezone handling has to wait until the backend upgrades this contract to RFC 3339 with an offset, or to a Unix timestamp. Until then, read `status` to decide whether a Session can still be paid rather than computing from this string.

That is an excerpt; the full field list is in [Create checkout session](https://docs.clinkbill.com/api-reference/endpoint/create-checkout-session.md). Two things to note:

* **The response contains no Publishable Key and no `environment`.** Both come from the merchant application config — see the next section
* The response **does** contain `url`, the hosted checkout address. An Elements integration does not use it

> [!WARNING]
>
> Do not forward Clink's raw response to the browser. The wrapper endpoint should return only what the frontend actually needs — ideally just `sessionId`.

## 2. Frontend: call the wrapper endpoint, then initialize

The browser does two things: ask the merchant backend for a `sessionId`, then initialize the SDK with it.

```javascript theme={null}
import { loadClinkElements } from '@clink-ai/clink-elements';

// This calls the merchant backend, not Clink
const response = await fetch('/api/payments/elements-session', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ productId, quantity }),
});

if (!response.ok) throw new Error('Unable to create checkout session');
const { sessionId } = await response.json();

const clink = await loadClinkElements({
  sessionId,
  publishKey: PUBLIC_CLINK_PUBLISHABLE_KEY,
  environment: 'sandbox',
  presetOptions: {
    locale: 'en-US',
    theme: 'light',
    primaryColor: '#1677FF',
  },
});
```

`PUBLIC_CLINK_PUBLISHABLE_KEY` and `environment` are **the application deployment config**, taken from the Publishable Key under **Developers > API Keys** (it starts with `pk_uat_`). They are safe to expose in the browser, but they do not come from the Create Session response.

> [tab] Vite
>
> ```bash theme={null}
> # .env
> VITE_CLINK_PUBLISHABLE_KEY=pk_uat_xxxxxxxx
> VITE_CLINK_ENVIRONMENT=sandbox
> ```

> [tab] Next.js
>
> ```bash theme={null}
> # .env.local
> NEXT_PUBLIC_CLINK_PUBLISHABLE_KEY=pk_uat_xxxxxxxx
> NEXT_PUBLIC_CLINK_ENVIRONMENT=sandbox
> ```

> [!NOTE]
>
> The SDK parameter is named `publishKey`. When this page says Publishable Key, that is the field it means — write `publishKey` in code.

## 3. Mounting, submitting, and third-party buttons

Two kinds of button can appear on a checkout page, and they behave differently:

**The merchant pay button** — for cards and anything else where the host triggers submission. Call `clink.submit()` on click.

**SDK built-in third-party buttons** — Apple Pay, Google Pay, PayPal, and similar. The `paymentMethod` element **renders these internally** and handles the click itself. When one takes over, the SDK emits `submit-visible: false` and the host page hides its own button.

```javascript theme={null}
const paymentMethod = clink.createElement('paymentMethod');
paymentMethod.mount('#payment-method');

// Only if customers pick a currency, and always after paymentMethod
const currencySelect = clink.createElement('currencySelect');
currencySelect.mount('#currency-select');

let canSubmit = false;
let submitting = false;

clink.on('submit-enabled', (enabled) => {
  canSubmit = enabled;
  payButton.disabled = !enabled || submitting;
});

// Hide the host button when a third-party button takes over
clink.on('submit-visible', (visible) => {
  payButton.hidden = !visible;
});

payButton.addEventListener('click', () => {
  if (!canSubmit || submitting) return;
  submitting = true;
  payButton.disabled = true;
  clink.submit();
});
```

> [!WARNING]
>
> Three things not to do:
>
> * **Do not hardcode button visibility by payment method name.** Follow `submit-visible`
> * **Do not draw a second set of Apple Pay, Google Pay, or PayPal buttons.** The SDK renders those; a hand-built copy does nothing when clicked
> * **Do not call `clink.submit()` for third-party buttons.** The SDK handles their clicks
>
> Which third-party methods appear depends on merchant configuration, the Session, currency, browser, and device. Do not promise a fixed set on the page.

`submit-enabled` reports whether submission is allowed. Write `disabled = !enabled` rather than passing the event value straight into `disabled`, which inverts the logic.

### Configure SDK button appearance

Starting with `0.0.3`, pass `sdkButtons` under `presetOptions` to configure Apple Pay, Google Pay, Link, and PayPal buttons.

```typescript theme={null}
import type { SdkButtonOptions } from '@clink-ai/clink-elements';

const sdkButtons: SdkButtonOptions = {
  applePay: {
    buttonHeight: 48,
    buttonRadius: 8,
    buttonTheme: 'black',
    buttonType: 'buy',
  },
  googlePay: {
    buttonHeight: 48,
    buttonRadius: 8,
    buttonTheme: 'black',
    buttonType: 'pay',
  },
  link: {
    buttonHeight: 48,
    buttonRadius: 8,
  },
  paypal: {
    buttonHeight: 48,
    buttonRadius: 8,
    buttonType: 'pay',
  },
};

const clink = await loadClinkElements({
  publishKey: PUBLIC_CLINK_PUBLISHABLE_KEY,
  environment: 'sandbox',
  sessionId,
  presetOptions: {
    locale: 'en-US',
    theme: 'light',
    sdkButtons,
  },
});
```

The public options are:

```typescript theme={null}
interface SdkButtonOptions {
  applePay?: {
    buttonHeight?: number;
    buttonRadius?: number;
    buttonTheme?: 'black' | 'white' | 'white-outline';
    buttonType?: 'buy' | 'check-out' | 'donate' | 'order' | 'plain';
  };
  googlePay?: {
    buttonHeight?: number;
    buttonRadius?: number;
    buttonTheme?: 'black' | 'white';
    buttonType?:
      | 'book'
      | 'buy'
      | 'checkout'
      | 'donate'
      | 'order'
      | 'pay'
      | 'plain'
      | 'subscribe';
  };
  link?: {
    buttonHeight?: number;
    buttonRadius?: number;
  };
  paypal?: {
    buttonHeight?: number;
    buttonRadius?: number;
    buttonType?: 'buynow' | 'checkout' | 'donate' | 'pay' | 'subscribe';
  };
}
```

| Button | Defaults | Configurable |
| - | - | - |
| Apple Pay | Height `45`, radius `6`, type `buy` | Height, radius, theme, type |
| Google Pay | Height `45`, radius `6`, theme `black`, type `pay` | Height, radius, theme, type |
| Link | Height `45`, radius `6` | Height, radius |
| PayPal | Height `45`, radius `6`, provider default type | Height, radius, type |

* Keep button height between `40` and `55` pixels for compatibility across the current button renderers
* A non-finite or non-positive height falls back to `45`; other unsupported positive values can make the affected button fail to initialize instead of falling back
* A non-finite or negative radius falls back to `6`; values above half the button height are capped at half the height
* Unsupported theme and type values fall back to their defaults
* Every SDK button uses `100%` width
* When Apple Pay has no explicit theme, light mode uses `black` and dark mode uses `white`
* Clink applies PayPal height and radius to a wrapper around the PayPal component rather than passing them as PayPal SDK options

Button options are read during initialization. To change them, destroy the current instance and call `loadClinkElements()` again.

### Track SDK button availability

Listen for `sdk-button-initialized` **before mounting `paymentMethod`** so the first event is not missed.

```typescript theme={null}
import type { SdkButtonInitializedData } from '@clink-ai/clink-elements';

const handleSdkButtonInitialized = (
  status: SdkButtonInitializedData,
) => {
  // { applePay: true, googlePay: false, link: true }
  console.log('Third-party button status', status);
};

clink.on('sdk-button-initialized', handleSdkButtonInitialized);

const paymentMethod = clink.createElement('paymentMethod');
paymentMethod.mount('#payment-method');
```

The payload type is:

```typescript theme={null}
type SdkButtonInitializedData = Partial<
  Record<'applePay' | 'googlePay' | 'link' | 'paypal', boolean>
>;
```

* `true` means the button initialized and is available on the current device
* `false` means the device is unsupported, the configuration is invalid, the gateway does not support it, the third-party SDK failed to load, or the button exceeded the 10-second timeout for its current initialization cycle
* Only buttons present in the current Session are included; the payload is `{}` when there are no third-party buttons

Each button's current loading cycle has a 10-second timeout. The event fires after all third-party buttons in the current round succeed, fail, or time out. A button that re-enters loading, or a change in available payment methods, starts a new waiting cycle. The event fires again after that cycle finishes, even when the result is unchanged.

### Track third-party payment dialogs

Listen for `sdk-dialog-open` and `sdk-dialog-close` to track when a third-party payment dialog opens or closes. The callback receives the payment method that triggered the event.

```typescript theme={null}
import type { SdkButtonType } from '@clink-ai/clink-elements';

clink.on('sdk-dialog-open', (paymentMethod: SdkButtonType) => {
  console.log('Third-party payment dialog opened', paymentMethod);
});

clink.on('sdk-dialog-close', (paymentMethod: SdkButtonType) => {
  console.log('Third-party payment dialog closed', paymentMethod);
});
```

The callback value is one of `applePay`, `googlePay`, `link`, or `paypal`.

### Configure currency selector styles

Starting with `0.0.5`, use `presetOptions.currencySelect` to customize the currency selector. Every style option is a standard CSS style object, written the same way as React's `style` prop.

```typescript theme={null}
const clink = await loadClinkElements({
  sessionId,
  publishKey: PUBLIC_CLINK_PUBLISHABLE_KEY,
  environment: 'sandbox',
  presetOptions: {
    currencySelect: {
      // Hide the selector when only one currency is available
      hideIfOneCurrency: true,
      switcher: {
        containerStyle: { gap: 8 },
        itemStyle: { borderColor: '#E7EBF3', background: '#FFFFFF' },
        selectedItemStyle: { borderColor: '#30343D', background: '#F5F5F5' },
        textStyle: { fontSize: 15, color: '#86909C' },
        selectedTextStyle: { color: '#30343D', fontWeight: 600 },
      },
    },
  },
});
```

| Option | Applies when | Styles |
| - | - | - |
| `hideIfOneCurrency` | Only one currency | Set to `true` to hide the whole selector. Defaults to `false` |
| `oneCurrencyStyle` | Only one currency | The amount text (currency symbol + amount) |
| `switcher.containerStyle` | Multiple currencies | The container that wraps all currency cards |
| `switcher.itemStyle` | Multiple currencies | Every currency card |
| `switcher.selectedItemStyle` | Multiple currencies | The selected currency card |
| `switcher.textStyle` | Multiple currencies | The amount text in every card |
| `switcher.selectedTextStyle` | Multiple currencies | The amount text in the selected card |

With multiple currencies, each option styles the following area (`[US]` and `[EU]` stand for flag icons):

```text theme={null}
┌─ containerStyle ──────────────────────────────────┐
│ ┌─ itemStyle ──────────┐ ┌─ itemStyle ──────────┐ │
│ │      ┌─ textStyle ─┐ │ │      ┌─ textStyle ─┐ │ │
│ │ [US] │ $99.00      │ │ │ [EU] │ €91.00      │ │ │
│ │      └─────────────┘ │ │      └─────────────┘ │ │
│ └──────────────────────┘ └──────────────────────┘ │
└───────────────────────────────────────────────────┘
```

* `oneCurrencyStyle` replaces the default style entirely, so set the font size, weight, and color yourself
* Options under `switcher` only override the properties you set; everything else keeps its default look
* The selected card applies `selectedItemStyle` and `selectedTextStyle` on top of `itemStyle` and `textStyle`; selected values win on conflicts
* Setting a border or background color in `itemStyle`, or a text color or weight in `textStyle`, overrides the default selected highlight — set the matching selected style as well
* When `hideIfOneCurrency` is `true` and only one currency is available, `oneCurrencyStyle` has no effect
* The heading, flag icons, and exchange-rate note cannot be customized yet

To change only the selected card's border, set just the properties that change in `selectedItemStyle`; everything else comes from `itemStyle`:

```typescript theme={null}
switcher: {
  itemStyle: { border: '1px solid #E7EBF3' },
  // Only the border color changes when selected; width and radius come from itemStyle
  selectedItemStyle: { borderColor: '#30343D' },
}
```

These options are read during initialization. To change them, destroy the current instance and call `loadClinkElements()` again.

### Use Express Checkout

Starting with `0.1.0`, `paymentMethod` supports an Express Checkout mode. It shows only the Apple Pay, Google Pay, PayPal, and Link express buttons.

Express Checkout is not a new element type. Turn it on by passing a second argument when creating `paymentMethod`:

```typescript theme={null}
import type { PaymentMethodElementOptions } from '@clink-ai/clink-elements';

const expressOptions: PaymentMethodElementOptions = {
  mode: 'expressCheckout',
  options: {
    paymentMethodOrder: ['applePay', 'googlePay', 'paypal', 'link'],
    buttonHeight: 48,
    buttonRadius: 8,
    sdkButtons: {
      applePay: { buttonTheme: 'black', buttonType: 'buy' },
      googlePay: { buttonTheme: 'black', buttonType: 'pay' },
      paypal: { buttonType: 'pay' },
      // Set to never to hide Link
      link: { visible: 'never' },
    },
  },
};

clink.on('session-success', () => {
  location.href = '/payment/result';
});

const paymentMethod = clink.createElement('paymentMethod', expressOptions);
paymentMethod.mount('#express-checkout');
```

Without the second argument, `paymentMethod` stays in standard mode and behaves as before.

#### How the two modes differ

| | Standard | Express Checkout |
| - | - | - |
| Renders | Payment method picker, card form, save payment method, third-party buttons | Express buttons only, plus billing address fields when the Session needs tax |
| Who starts payment | The host calls `clink.submit()` for cards and similar; the SDK handles third-party buttons | The buttons themselves — **no** host pay button is needed |
| `clink.submit()` | Starts payment | Does not start payment; logs a console warning |
| `submit-visible` | Emitted | Not emitted |
| Button styles | `presetOptions.sdkButtons` | `options` in the second `createElement` argument; `presetOptions.sdkButtons` is **ignored** |

Shared options in `presetOptions` — `locale`, `theme`, `primaryColor`, `radius`, and so on — still apply in Express Checkout. You can also create and mount `currencySelect` as usual.

#### Options

The full type is:

```typescript theme={null}
type ExpressCheckoutPaymentMethod = 'applePay' | 'googlePay' | 'paypal' | 'link';
type ExpressCheckoutVisible = 'auto' | 'never';

interface ExpressCheckoutOptions {
  paymentMethodOrder?: ExpressCheckoutPaymentMethod[];
  buttonHeight?: number;
  buttonRadius?: number;
  hideError?: boolean;
  sdkButtons?: {
    applePay?: {
      visible?: ExpressCheckoutVisible;
      buttonTheme?: 'black' | 'white' | 'white-outline';
      buttonType?: 'buy' | 'check-out' | 'donate' | 'order' | 'plain';
    };
    googlePay?: {
      visible?: ExpressCheckoutVisible;
      buttonTheme?: 'black' | 'white';
      buttonType?:
        | 'book'
        | 'buy'
        | 'checkout'
        | 'donate'
        | 'order'
        | 'pay'
        | 'plain'
        | 'subscribe';
    };
    paypal?: {
      visible?: ExpressCheckoutVisible;
      buttonType?: 'buynow' | 'checkout' | 'donate' | 'pay' | 'subscribe';
    };
    link?: {
      visible?: ExpressCheckoutVisible;
    };
  };
}
```

| Option | Default | Description |
| - | - | - |
| `paymentMethodOrder` | Session order | Top-to-bottom button order — see the ordering rules below |
| `buttonHeight` | `45` | Applies to every button. A non-finite or non-positive value falls back to the default |
| `buttonRadius` | `6` | Applies to every button. A non-finite or negative value falls back to the default; values above half the height are capped at half the height |
| `hideError` | `false` | When `true`, the element shows no error message so the host page can show its own; the `error` event still fires |
| `sdkButtons.*.visible` | `'auto'` | `'auto'`: show when the Session returns it and the current device supports it. `'never'`: always hide |
| `sdkButtons.applePay` / `googlePay` | Same as [Configure SDK button appearance](#configure-sdk-button-appearance) | Accept `buttonTheme` and `buttonType` |
| `sdkButtons.paypal` | PayPal default type | Accepts `buttonType` |
| `sdkButtons.link` | — | Accepts `visible` only |

* Height and radius are set once for all buttons; per-button values are not supported
* Button labels come from the third-party SDK through `buttonType`
* Buttons stack vertically with an `8px` gap and fill the container width

#### Button order and visibility

When `paymentMethodOrder` is set:

1. Buttons follow the configured order (case-insensitive; duplicates and unsupported values are ignored)
2. Methods the Session returns but the list omits are appended in their original Session order

For example, if the Session returns `paypal, applePay, googlePay` and the option is `['googlePay']`, the final order is `googlePay, paypal, applePay`.

A button shows only when all three hold:

* The Session returns that payment method (depends on merchant configuration, currency, and so on)
* Its `visible` is not `'never'`
* The current browser and device support it, and the third-party SDK initializes

Listing a button in the options does not guarantee it appears. Listen for [`sdk-button-initialized`](#track-sdk-button-availability) to learn which buttons are actually available.

> [!NOTE]
>
> When the Session has **no** express payment methods at all, the element renders nothing — not even the address fields — and logs a console warning.

#### Billing address and tax

When the Session needs tax, the element shows the required address fields — country, address, city, postal code, and so on — above the buttons. When the customer changes the address, Clink recalculates tax and updates the amount; the buttons are temporarily disabled meanwhile.

The new amount is also sent to the host page through `amount-change`. Use the amount from that event in your order summary.

#### Events

Express Checkout reuses the existing events; there is nothing new to listen for:

| Event | Use in Express Checkout |
| - | - |
| `session-init-success` | Clear the host skeleton state |
| `sdk-button-initialized` | Read which buttons are actually available |
| `sdk-dialog-open` / `sdk-dialog-close` | Track third-party payment dialogs opening and closing |
| `amount-change` | Update the order summary when an address change updates tax |
| `session-success` / `session-pending` | Navigate to the result page or show "confirming payment" |
| `error` | Tax calculation or payment failed |

`submit-enabled` and `submit-visible` exist for the host pay button and need no handling in Express Checkout.

#### Limits

* `mode` is fixed at creation and cannot be switched later. To change modes, destroy the instance and call `loadClinkElements()` again
* One instance can create only one `paymentMethod`, so a single instance cannot provide both the standard payment form and Express buttons
* As in standard mode, `session-success` is not proof of payment; the final status comes from the webhook your backend receives

## 4. Events

Two groups, by what they are used for.

**Update host UI**

| Event | What to do |
| - | - |
| `session-init-success` | Clear the host skeleton state |
| `submit-enabled` | Enable or disable the pay button and promo code controls |
| `submit-visible` | Hide the host pay button when a third-party button takes over |
| `sdk-button-initialized` | Read which third-party buttons are available on the current device |
| `sdk-dialog-open` | Track when a third-party payment dialog opens and which payment method triggered it |
| `sdk-dialog-close` | Track when a third-party payment dialog closes and which payment method triggered it |
| `amount-change` | Update total, currency, discount, tax, and button label |
| `promo-code-error` | End the promo code loading state and show a field-level error |
| `error` | Branch by error type — see the table below |

**Flow signals**

| Event | What to do |
| - | - |
| `session-success` | Navigate to the merchant result page |
| `session-pending` | Show a "confirming payment" state |

> [!WARNING]
>
> `session-success` is **not proof of payment**, and neither is `returnUrl`. Browser events can be forged.
>
> Do this instead: on `session-success`, navigate to the merchant result page, and have that page query **the merchant backend** for the order status. Shipping, top-ups, and entitlements are decided by the backend from signature-verified webhooks and server-side queries.
>
> Verification, deduplication, and order matching are covered in [Hosted Checkout](https://docs.clinkbill.com/build-integration.md).

## 5. Promo codes

Optional. Creating Coupons and Promotion Codes server-side is covered in [Discounts and promotion codes](https://docs.clinkbill.com/promotions.md). This section is frontend only.

```javascript theme={null}
clink.on('amount-change', ({ amount }) => {
  promoSection.hidden = !amount.enablePromotionCode;
  renderApplied(amount.promotionCodeInfo);
  updateTotal(amount.dueTodayAmount, amount.currency);
});

applyButton.addEventListener('click', () => {
  setPromoLoading(true);
  clink.promoCodeChange({ type: 'apply', code: promoInput.value });
});

removeButton.addEventListener('click', () => {
  setPromoLoading(true);
  clink.promoCodeChange({ type: 'clear' });
});

clink.on('promo-code-error', ({ message }) => {
  setPromoLoading(false);
  showPromoError(message);
});
```

The payload is `{ amount }`, with the fields nested under `amount`. Writing `(info) => info.enablePromotionCode` yields `undefined`, and the promo code entry never appears.

Discounts and the final amount due come from `amount`. Do not recompute them.

## 6. Error handling

`0.0.5` throws three different kinds of thing, and they are handled differently.

### Initialization: `loadClinkElements()`

It does **not** throw only `ClinkApiError`. There are at least three paths:

| What is thrown | When |
| - | - |
| `ClinkApiError` | A Clink endpoint returned non-2xx, or the response body had `code !== 200` |
| Native `TypeError` | The request never completed — offline, DNS, CORS, or blocked |
| Native `Error` | `environment` was an unrecognized value; the message is `Unknown environment: xxx` |

A response body that is not valid JSON also surfaces as a native `SyntaxError` from `await res.json()`.

So treat the `catch` parameter as `unknown` and **always keep a fallback branch**:

```typescript theme={null}
import { loadClinkElements, ClinkApiError } from '@clink-ai/clink-elements';

try {
  const clink = await loadClinkElements(options);
} catch (error: unknown) {
  if (error instanceof ClinkApiError) {
    // A business error from a Clink endpoint; message comes from the API
    showInitError(error.message);
  } else if (error instanceof TypeError) {
    // Network or transport failure — offer a retry
    showNetworkError();
  } else {
    // Bad arguments, response parsing failures, anything else
    showUnknownError(error);
  }
}
```

> [!WARNING]
>
> `0.0.5` also exports `SessionExpiredError`, `SessionCompleteError`, `SessionLoadError`, `SessionNotSupportedError`, and `PromoCodeError`. In the shipped build those are **class definitions with no throw sites at all**.
>
> **Do not write `instanceof` branches against them** — the conditions never hold. Revisit once a later version actually uses them.

When an initialization error does arrive, check these. Each has its own source of truth — do not attribute all three to one endpoint:

| What to check | Where the answer comes from |
| - | - |
| Do `publishKey`, `environment`, and `sessionId` belong to the same environment | The configuration each one came from; a sandbox key against a production Session fails |
| Did the backend send `uiMode: elements` | The Create Session request, or the `uiMode` returned by the Session API |
| Has the Session expired or already been paid | The `status` returned by the Session API — do not infer it in the browser |

### After initialization: some errors are thrown synchronously

**Not every runtime problem arrives as an event.** These are **synchronously thrown native `Error`s** and need a `try/catch`:

| Message | Trigger |
| - | - |
| `Element "xxx" already created` | The same element type was created twice on one instance |
| `currencySelect cannot be created without paymentMethod` | `currencySelect` was created first |
| `Element "xxx" is already mounted` | `mount()` called twice on the same element |
| `Mount target not found: xxx` | The `mount()` selector matches nothing on the page |
| `ClinkElements instance has been destroyed` | The instance was used after `destroy()` |

```javascript theme={null}
try {
  const paymentMethod = clink.createElement('paymentMethod');
  paymentMethod.mount('#payment-method');
} catch (err) {
  // Creation order, duplicate creation, and missing mount targets all land here
  reportIntegrationBug(err);
}
```

### Errors during the payment flow: events

Errors that belong to the payment flow itself are forwarded from the checkout iframe as events, and are not wrapped in any error class.

| Event | When | What to do |
| - | - | - |
| `error` | Something failed during payment | Show the message from the event data and keep the form usable |
| `promo-code-error` | The promo code is invalid | Show it in the promo area only, leaving the payment form alone |

## 7. Implementation constraints

Get these wrong and the integration breaks. Everything else about layout is a free design decision.

| Constraint | What goes wrong | What to do |
| - | - | - |
| One instance per Session | Reusing an old Session loads a completed or expired state | Destroy the old instance and reinitialize when `sessionId` changes |
| Fixed creation order | Creating `currencySelect` first throws | `paymentMethod` first, then the optional `currencySelect`; each element type once per instance |
| Teardown must clean up | Orphaned iframes and window message listeners | Call `destroy()` on route change or component unmount. Repeat calls are safe to ignore, but a destroyed instance cannot be reused |
| Stable container with flexible height | Wallet, QR code, or 3DS interactions get clipped | Do not give the payment iframe's parent a fixed height, and do not clip dynamic content with `overflow: hidden` |
| Browser-only execution | SSR fails when it touches the DOM | In Next.js and similar, put it in a client component or a client-side init step |

## Before shipping

* [ ] No Secret Key and no webhook signing key in browser Network traffic or the build output
* [ ] The browser only calls the merchant Session wrapper endpoint, never Clink's Create Session directly
* [ ] The backend does not trust a final amount from the browser; it recalculates from the product or cart
* [ ] The local order, `merchantReferenceId`, and `sessionId` mapping is stored
* [ ] The Publishable Key and `environment` come from application config, and are not described as Create Session response fields
* [ ] `submit-visible` hides the host button when Apple Pay, Google Pay, PayPal, or similar appear
* [ ] With Express Checkout, the page has no host pay button and handles the case where no button is available
* [ ] `session-success` does not trigger fulfillment; the final state comes from verified webhooks and backend queries
* [ ] Old instances are destroyed when the Session changes or the page unmounts

## Next

> [card] [Hosted Checkout](https://docs.clinkbill.com/build-integration.md)
>
> The backend and webhook halves are identical to Hosted Checkout.

> [card] [Go live](https://docs.clinkbill.com/go-live.md)
>
> The checklist before switching to production.


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