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

# API Keys & Webhooks

> Generating, rotating, and restricting API keys; registering, verifying, and receiving webhooks.

This page is the configuration reference. To run one payment end to end, start with the [Quickstart](https://docs.clinkbill.com/quickstart.md); for implementation code, see [Hosted Checkout](https://docs.clinkbill.com/build-integration.md).

## Environments

Clink has a sandbox and a production environment. The sandbox is what people usually call the test environment.

| | Sandbox | Production |
| - | - | - |
| Dashboard | `https://uat-dashboard.clinkbill.com` | `https://dashboard.clinkbill.com` |
| API | `https://uat-api.clinkbill.com` | `https://api.clinkbill.com` |
| Secret Key | `sk_uat_…` | `sk_prod_…` |
| Publishable Key | `pk_uat_…` | `pk_prod_…` |

> [!WARNING]
>
> These are two separate dashboards. Sandbox payment-domain resources and environment-specific configuration are not copied to production, including products, customers, orders, API keys, webhook endpoints, signing keys, and verification applications and details. On first access to production, Clink synchronizes the tenant, merchant, user sign-in credentials, and role assignments required for production access. Debug thoroughly in the sandbox before deploying to production, and do not use real customer data in the sandbox.

## API keys

Clink authenticates requests with two headers:

```json theme={null}
{
  "X-API-Key": "sk_uat_*********************",
  "X-Timestamp": "${currentMillisecondsTimestamp}"
}
```

`X-Timestamp` is a millisecond timestamp. **In production, it must be within 2 minutes of platform time**, ahead or behind. Compute it per request rather than hardcoding or caching one.

> [!WARNING]
>
> **The sandbox is far more lenient** — currently ±24 hours. That is a testing convenience, not an interface guarantee, and it can be tightened at any time.
>
> Passing in the sandbox therefore does not mean passing in production. A cached timestamp, a hardcoded one, or an unsynced server clock all sail through the sandbox and then fail authentication across the board once traffic moves to production. Generate the value at call time, and keep the server clock on NTP.

Both values are hot-reloadable configuration and may change.

### Initialize a key

Go to **Developers** and click **Initialize Key**. The Secret Key is displayed once — copy and store it.

> [accordion] Generate an API key
>
> ![key](https://mintcdn.com/clink/peBNaRlFWIQS8vOQ/images/empty_key.png?fit=max\&auto=format\&n=peBNaRlFWIQS8vOQ\&q=85\&s=e7c912986938e46a3c33cd39c37d707f)

### The two key types

**Secret Key** (`sk_`) authenticates server-side API calls. By default it is unrestricted and can perform any API request, including taking payments and issuing refunds.

> [!WARNING]
>
> The Secret Key belongs on the server only. Keep it out of frontend code, out of version control, and out of app bundles.

**Publishable Key** (`pk_`) is used in the browser. It can reach exactly two client-side SDK endpoints:

* `/api/sdk/bootstrap`
* `/api/checkout/session/verify-merchant`

Every other `/api/**` endpoint requires the Secret Key. A Publishable Key therefore cannot create Checkout Sessions, read orders, or issue refunds; those operations are server-side only.

### Rotate a key

Rotating revokes the current key and generates a replacement. The old key can be expired immediately or given a window to allow a gradual cutover.

**1. Open the API keys page**

Go to **Developers**.

**2. Choose rotate**

Click the overflow button (⋮) on the key's row and select **Roll Key**.

**3. Set the expiry**

Pick how long the old key stays valid. In production, leave an overlap so the new key can be deployed before the old one dies.

**4. Save the new key**

Copy the new value from the dialog. It cannot be retrieved later.

### Delete a key

Deleting stops API calls with that key immediately. A key that is the last valid one on the account **cannot** be deleted.

Rotate to a new key first, update the code, confirm production is using it, then delete the old one.

### Restrict by IP

Only Secret Keys support IP restrictions. Requests can be limited to specific IPs, or to a range using [CIDR](https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing).

Click the overflow button (⋮) on the key's row, select **Manage IP Restrictions**, enable *Restrict usage to a set of IP addresses*, then add IPs or CIDR ranges one at a time.

> [!NOTE]
>
> Update this whenever the server's egress IP changes, or every API request starts failing.

## Webhooks

Webhooks are how Clink pushes results out. Payment results, refunds, and subscription renewals all reach the merchant server this way.

### Register an endpoint

**In the dashboard**: go to **Developers > Webhooks**, click **Add**, enter an HTTPS URL, and select the events to subscribe to.

**Through the API**: call [`PUT /webhook/endpoints/ensure`](https://docs.clinkbill.com/api-reference/endpoint/ensure-webhook-endpoint) with `url` and `events`. This endpoint is idempotent on the URL — calling it repeatedly updates rather than duplicating, which makes it suitable for deployment scripts.

**Through the CLI**: `clink-integ-cli` combines registration and secret sync into one step:

```bash theme={null}
export CLINK_INTEG_CLI=/path/to/clink-integ-skills/vendor/clink-integ-cli/clink-integ-cli

node "$CLINK_INTEG_CLI" webhook endpoint ensure \
  --url https://your-site.com/api/webhooks/clink \
  --events session.complete,session.expired,order.created,order.next_action,order.succeeded,order.failed,refund.created,refund.succeeded,refund.failed \
  --save-secret \
  --sync-env-file .env.local \
  --json
```

> [!WARNING]
>
> **Do not use `--events core`.** It subscribes to six events — `session.complete`, `order.succeeded`, `order.failed`, `refund.succeeded`, `subscription.created`, `invoice.paid` — and **omits `order.created` and `order.next_action`**.
>
> Without `order.created` there is no basis for ordering payment attempts; without `order.next_action`, orders that need extra customer verification stay stuck in a pending state. The multi-attempt model in [Hosted Checkout](https://docs.clinkbill.com/build-integration.md) cannot run on `core`.
>
> That is why the nine event names are listed explicitly above. Once `clink-integ-cli` ships a `checkout` or `commerce` preset, `--events checkout` can replace the list.

`--save-secret` stores the returned signing secret in the CLI profile and `--sync-env-file` writes it into the given env file. **A restart or redeploy is still required** before the service loads it. Rerun this whenever the webhook URL changes, then sync and restart again.

The tool ships with [clink-integ-skills](https://github.com/clinkbillcom/clink-integ-skills). It is not the npm package [`@clink-ai/clink-cli`](https://docs.clinkbill.com/api-reference/clink_cli), which is the customer wallet CLI — both start with `clink`, so check which one is installed.

> [!WARNING]
>
> The webhook URL must be publicly reachable over HTTPS. localhost, loopback, private, link-local, and multicast addresses are all rejected.

`GET /webhook/events` returns the currently supported event names. Register with event names, not numeric codes.

When the API returns or rotates a `signingSecret`, store it in the server-side secret manager, then restart or redeploy.

### Verify signatures

Clink signs every event with HMAC SHA-256. The signing key becomes available once an endpoint is registered.

Three headers carry the signature:

| Header | Contains |
| - | - |
| `X-Clink-Timestamp` | Unix timestamp in **milliseconds** |
| `X-Clink-Signature` | Clink's signature, hex encoded |
| `X-Clink-SignType` | The algorithm; currently `SHA256` |

Run these in order:

**1. Check the signature type**

`X-Clink-SignType` must be `SHA256`. Reject anything else rather than computing further.

**2. Check timestamp freshness**

`X-Clink-Timestamp` is a Unix millisecond timestamp. Require `abs(now - timestamp) <= 5 minutes`.

Reject anything outside the window, anything non-numeric, and anything arriving while the receiving clock is badly skewed. Keep the server on NTP.

**3. Build the signing string**

The timestamp as a string, then the character `.`, then the raw request body exactly as received.

**4. Compute the HMAC**

HMAC-SHA256 with the signing key, hex encoded.

**5. Compare in constant time**

Process the event only if it matches `X-Clink-Signature`. **The comparison must be constant-time** (`crypto.timingSafeEqual` on Node); a plain `===` leaks how far the byte-by-byte match got.

> [!WARNING]
>
> **Both the freshness check and the HMAC must complete before the JSON is parsed, against the raw body.** Parsing and re-serializing changes key order and whitespace, and the signature will never match.
>
> Note also that the time window stops replays but **not duplicates** — Clink's own retries land inside it. Deduplicate separately and atomically on `event.id`; see [Hosted Checkout](https://docs.clinkbill.com/build-integration.md).

Copy-pasteable verification code is in the "Verifying the signature" section of [Hosted Checkout](https://docs.clinkbill.com/build-integration.md).

### Delivery rules

Non-2xx responses and timeouts both count as failed delivery. After the first failure, delivery is retried with exponential backoff.

Under the current policy the waits are approximately **2, 4, 8, 16, 32, 64, 128, 256, and 512 minutes**, for a maximum of **10 HTTP delivery attempts including the first**. If delivery keeps failing, the last actual HTTP attempt lands roughly **17 hours** after the first, and the event then moves to the dead-letter queue.

Those nine waits total 1022 minutes, about 17 hours 2 minutes. Queue scheduling introduces small deviations.

> [!WARNING]
>
> Retry intervals are platform configuration and may change. **Do not hardcode them** into business logic, alert thresholds, or compensation job schedules, and do not depend on minute-level precision.
>
> Where a safety net is needed, schedule the reconciliation pass after the retry window closes — for example, if an event has still not arrived about **18 hours** after it was first due, pull the state through `GET /order/{orderId}` or a similar endpoint.

**Retry exhaustion must be evaluated per event, not from the total outage duration.** An event may have exhausted all automatic attempts when recovery occurs roughly **17 hours** or more after that event's first delivery. Events first delivered shortly before recovery may still be inside their retry window.

For example, in a 20-hour outage the events first delivered at the start are long past their last attempt, while events first delivered an hour before recovery will still be retried. The same outage puts them in completely different positions.

After recovery, reconciling the **entire outage interval** remains the conservative operational policy. Check the Orders, Invoices, Subscriptions, and Refunds inside it through the server-side query or list endpoints rather than assuming a push will fill the gap. Where an operational rule needs a round number, **18 hours** is a safe rounding of the 17 hour 2 minute window — not a separate platform threshold.

Individual events can be resent from the dashboard: open the transaction detail, find the **Webhook delivery** list, and resend to a specific endpoint. That is a one-at-a-time action; there is no bulk replay.

**Events are not guaranteed to arrive in the order they occurred.** Handlers must not depend on ordering, and an earlier event must never overwrite a later state.

Because of retries, the same event arrives more than once. Deduplicate on the event's `id` field.

### Common events

| Resource | Events |
| - | - |
| Session | `session.complete`, `session.expired` |
| Order | `order.created`, `order.next_action`, `order.succeeded`, `order.failed` |
| Refund | `refund.created`, `refund.succeeded`, `refund.failed` |
| Subscription | `subscription.created`, `subscription.trialing`, `subscription.activated`, `subscription.past_due`, `subscription.cancelled`, `subscription.incomplete_expired`, `subscription.updated.plan_changed`, `subscription.updated.plan_change_canceled`, `subscription.updated.renewed`, `subscription.updated.cancel_at_period_end_set`, `subscription.updated.cancel_at_period_end_revoked` |
| Invoice | `invoice.open`, `invoice.paid`, `invoice.void` |
| Dispute | `dispute.created`, `dispute.updated`, `dispute.won`, `dispute.lost`, `dispute.closed` |
| Customer | `customer.verify` |

For Hosted Checkout, explicitly dispatch both Session terminal events. `session.complete` updates only the Session lifecycle to `completed`; `session.expired` updates it only to `expired`. Store the outer `event.created` as the Session lifecycle version: an older terminal event cannot overwrite a newer one, and two different terminal states at the same millisecond require durable manual review. Neither event is evidence that an Order succeeded or failed, so payment, refund, fulfillment, and Payment Attempt state remain separate.

Payload structures are in the [Webhook reference](https://docs.clinkbill.com/api-reference/webhook/order.md). Endpoint management is in [Webhook Endpoint Management](https://docs.clinkbill.com/api-reference/endpoint/list-webhook-endpoints.md).

### Rotate the signing secret

Call [`POST /webhook/endpoints/{id}/rotate-secret`](https://docs.clinkbill.com/api-reference/endpoint/rotate-webhook-signing-secret).

After rotating, update the signing key on the server and restart. Otherwise every newly delivered event fails verification.

## The dashboard

Day-to-day operations happen in the dashboard:

> [card] [Merchant](https://docs.clinkbill.com/guides/account/merchant.md)
>
> The business operating unit.

> [card] [User](https://docs.clinkbill.com/guides/account/user.md)
>
> A dashboard account owner.

> [card] [Product & Price](https://docs.clinkbill.com/guides/resources/product.md)
>
> The selling unit and pricing configuration.

> [card] [Balances](https://docs.clinkbill.com/finance/balance.md)
>
> Account balances and fees.


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