# Authentication & API keys

Every request to `/payments-api/v1` authenticates with a **secret API key** sent as a Bearer token. A key is scoped to a single seller account and grants full API access — treat it like a password.

## The auth header

Include the key in every request as an HTTP Bearer token:

```http
Authorization: Bearer <your_key>
```

Anything else — missing header, malformed value, or an unrecognised key — returns `401 Unauthorized`.

## How to get a key

You issue your own keys — there is no need to wait on the Fynex team.

**From the dashboard (easiest):**

1. Log in to the dashboard (`https://dashboard.fynex.ai`) with your username and password.
2. Select your seller account.
3. Open **Developers** in the menu and find the **API keys** card.
4. Click **New secret key**. The key is shown **once** — copy it now and put it in your secret manager. Leaving the page discards it; if you lose a key, issue another one and revoke the lost one.

The value you copy is exactly what you pass as `Authorization: Bearer <key>`. It is prefixed `sk_test_…` while the account is in Demo mode and `sk_live_…` once the account has gone live. The same card also issues **publishable** keys (`pk_…`); those identify the account in a browser and do not authenticate this API — a publishable key sent as a Bearer token is refused like any unknown key.

If you don't have a dashboard login yet, sign up self-service (see
**Programmatically** below).

**Programmatically:** `POST /api/v1/onboarding/start` (sign-up; sets the session cookie itself) — or, for an existing account, `POST /api/v1/login/dashboard` (which sets the
session cookie) → create the seller account in the Fynex dashboard, which issues its legacy `authorizationToken` (see [What a key looks like](#what-a-key-looks-like)). That
token works as a Bearer token straight away; issue a secret key for it from the dashboard when you
can. See the
[Account setup & onboarding](https://docs.fynex.ai/payments-api/v2/docs#tag/onboarding) guide for the full walkthrough.

Keys are managed from the dashboard on purpose: the routes behind that card (`/api/v1/developer/api-keys`, documented under [Naming and expiring keys](#naming-and-expiring-keys)) take a dashboard session or the account's legacy token and refuse an `sk_` key, so a leaked key cannot mint the replacement that outlives its own revocation.

> [!IMPORTANT]
> A new seller account is created in `Demo` mode and **activated automatically**, so your key
> works immediately for **sandbox testing** — you can take test payments straight away (see the
> [Quickstart](https://docs.fynex.ai/payments-api/v2/docs#tag/quickstart)). **Going live** (real-money processing) is separate: it requires
> KYB approval and a Fynex-assigned live acquirer terminal. If a sandbox call ever returns
> `403 seller account is not active`, the key is still valid — the account just isn't active
> yet; contact Fynex with your seller account ID.

> [!NOTE]
> Keys are issued per seller account, and each environment's dashboard issues its own — a key only works against the API host of the dashboard that issued it.

> [!CAUTION]
> **Regenerate** on the API keys card revokes a key and issues its replacement in one click, and **Revoke** disables a key with no undo. Both take effect immediately — that key has no overlap window. To rotate without downtime, issue a second key first (see [Rotating a key](#rotating-a-key)).

## What a key looks like

There are three credential shapes on this API, and which one you have depends on
how you got it:

- **Secret key** (Developers → API keys, above). Prefixed
  `sk_test_…` while the account is in demo mode and `sk_live_…` once it has
  gone live. This is what a new integration uses.
- **Legacy authorization token.** Accounts created before API keys existed also
  hold an opaque long-lived string with no prefix, shown on the Developers page
  under **Authorization Token** and labelled legacy. It still authenticates this
  API, but it cannot be rotated without downtime (regenerating replaces the only
  copy), so move such an integration to a secret key.

All of them authenticate identically as a Bearer token on the Payments API. Don't
assume every credential on this API carries an `sk_` prefix — the legacy shape
doesn't. Treat the whole value as opaque either way.

The **Billing API** (`/billing-api/v1`) is stricter: it accepts only
`sk_test_…` / `sk_live_…` secret keys and answers `401` to the prefix-less
legacy token. If you need both APIs, use an `sk_` key for both — one key
authenticates both surfaces, the legacy token authenticates only this one.

## Verifying a key

The quickest "is this key alive, and which account is it?" check is `GET /account`. It requires only a valid key and returns the account the key acts for — including `operationalMode`, which tells you whether you are in `Demo` (test cards, no real money) or `Live`.

```bash
curl -sS "$FYNEX_API/account" \
  -H "Authorization: Bearer $FYNEX_TOKEN"
```

```json
{
  "sellerAccountUuid": "3f2b1c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d",
  "name": "Acme Marketplace",
  "operationalMode": "Demo",
  "status": "Active",
  "currency": "EUR",
  "selfServeSandbox": false,
  "features": { "walletCreation": true, "payeePayoutAutoFunding": true, "refunds": true }
}
```

A `200 OK` JSON response confirms the key works and the account is active. A `401` means the key is missing, malformed, or invalid. A `403 seller account is not active` means the key is **valid and recognised** but the account isn't active — contact Fynex with your seller account ID (see [How to get a key](#how-to-get-a-key)).

## Storing keys securely

- **Never commit keys to source control.** Use a secret manager (HashiCorp Vault, AWS Secrets Manager, GitHub Encrypted Secrets) or environment variables loaded at runtime.
- **One key per environment.** Keep staging and production keys separate.
- **One key per seller account.** There is no cross-account access; operate multiple sellers with one key each.
- **One key per integration.** A seller account can hold several secret keys, so give each system (your backend, a plugin, a reporting job) its own, named after it; revoking one then stops only that system. A job that only reads can get a [restricted key](#restricted-keys).

```bash
# .env — never commit this file
FYNEX_TOKEN=<your_key_here>
FYNEX_API=https://api.fynex.ai/payments-api/v1
```

## Rotating a key

Secret keys coexist, so a rotation needs no downtime:

1. Issue a new secret key on the **Developers → API keys** card.
2. Deploy it to every service that used the old key.
3. **Revoke** the old key on the same card. Revocation is immediate and has no undo.

**Regenerate** does steps 1 and 3 in one go. On the dashboard card the old key stops working the moment the new one is issued — use that when you can tolerate the gap, a leaked key for instance. Through the API, `overlapHours` keeps the old key working beside its replacement for up to 7 days (see [Rotating an API key without an outage](#rotating-an-api-key-without-an-outage)).

A **legacy authorization token** has no overlap window: the **Regenerate** button on the seller account in the Fynex dashboard replaces the only token immediately and shows the new `authorizationToken`. Plan a brief restart, or move the integration to a secret key first and rotate that instead.

### When to rotate

- A developer with access leaves the team.
- You suspect or confirm a key leak.
- As a precautionary measure on a regular schedule (quarterly is a common default).

## Rotating an API key without an outage

`sk_` API keys rotate with an overlap: regenerating a key through the API can leave the old one
working for up to 7 days beside its replacement, so you deploy the new key first and let the old one
lapse. Regenerating answers with the replacement's plaintext, once; the replacement keeps the old
key's name, permissions and lifetime.

```bash
# $FYNEX_TOKEN is the account's legacy dashboard token (Developers page), not an sk_ key.
curl -sS -X POST https://api.fynex.ai/api/v1/developer/api-keys/<id>/regenerate \
  -H "Authorization: Bearer $FYNEX_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"overlapHours": 24}'
```

- `overlapHours` — `0` to `168`. `0`, or no body at all, stops the old key at once, which is what
  **Regenerate** on the dashboard card does.
- `expiresAt` — optional RFC 3339 time at which the replacement stops working. Without it the
  replacement lives as long as the old key was issued to, counted from now: a 30-day key regenerated
  today expires in 30 days, and a key that never expired is replaced by one that never expires.

Key management needs the legacy dashboard token or a dashboard session: an `sk_` key cannot create,
regenerate or revoke keys.

## Naming and expiring keys

Give each integration its own key — production, CI, one per agent — so one can be revoked without
touching the others. `POST /api/v1/developer/api-keys` takes:

| Field | Required | Meaning |
|-------|----------|---------|
| `type` | yes | `secret` or `publishable` |
| `name` | no | What the key is for, up to 64 characters. Shown in the key list |
| `expiresAt` | no | RFC 3339 time at which the key stops working, at least a minute ahead. Omit it for a key that never expires |

A key used after its `expiresAt` is refused with `401` `api_key_expired`. The key list reports it
with `status: "expired"`; create or regenerate a key to replace it.

## Restricted keys

A secret key can be **restricted** to what one integration needs: a reporting agent that reads
payments and events, a metering job that only submits usage. Pass `permissions` when you create it:

```json
{ "type": "secret", "name": "metering", "permissions": ["billing_usage:write"] }
```

Each permission is a resource at `read` or `write`; `write` includes `read`. Without `permissions`
the key has full access, as every key had before.

| Resource | Covers |
|----------|--------|
| `payments` | Payments, checkout sessions, capture, payment methods, settling a test payment |
| `refunds` | Refunds and their cancellation, cancelling a promotion-paid order |
| `payees` | Payees |
| `payout_methods` | Payout methods, the seller's own and its payees' |
| `payouts` | Payouts |
| `wallets` | Wallets, their funding and transactions |
| `topups` | Top-up invoices |
| `split_rules` | Split rules and a payment's split decisions |
| `webhooks` | Webhook endpoints and the allowlist |
| `events` | The events feed |
| `vendors` | Marketplace vendors |
| `billing_contracts` | Billing customers, contracts, credits, prices and the test clock |
| `billing_subscriptions` | Subscriptions |
| `billing_invoices` | Billing invoices |
| `billing_usage` | Usage events, business events, metrics, dead letters and usage webhook endpoints |

Every operation in the OpenAPI documents states the permissions it needs in
`x-fynex-permissions`. A restricted key calling an operation it lacks a permission for is refused
with `403` `insufficient_scope`, and the message names what is missing:

```json
{ "error": "this API key is restricted: this route needs payouts:write", "code": "insufficient_scope" }
```

A restricted key reaches only the documented Payments and Billing operations, under
`/payments-api/v1` and `/billing-api/v1`, and the MCP endpoint. `GET /account` works with any key
and reports the calling key's `access` and `permissions` under `apiKey`, so an integration can check
what it may do. Regenerating a restricted key keeps its permissions; only a secret key can be
restricted.

## OAuth for AI clients (MCP)

Not yet available on production.

## Key properties

| Property | `sk_` API key | Legacy dashboard token |
|----------|---------------|------------------------|
| Scope | Single seller account | Single seller account |
| Expiry | None, or the `expiresAt` you set per key | None |
| Revoke | Any key, at any time — immediate, no undo | None — regenerate to invalidate |
| Rotation | With up to 7 days of overlap, or at once | Replaces the token at once |
| Several per account | Yes, each with its own name | No — one per seller account |
| Permissions | Full access, or restricted to listed permissions | Full access |
| Environment | `sk_test_` while the account is in Demo mode, `sk_live_` once it is Live; when the account goes live its test keys stop working with `401` `key_environment_mismatch` — issue an `sk_live_` key | Follows the account |
| Rate limiting | Per-seller token-bucket rate limit; the budget differs by environment — read `X-RateLimit-Limit` / `X-RateLimit-Remaining` rather than assuming a rate. Returns `429` with a `Retry-After` header when exceeded | Same |


## Common errors

| Status | Body | Cause |
|--------|------|-------|
| `401` | `{"error": "authorization token is required", "code": "missing_api_key"}` | Header absent or malformed at the middleware level |
| `401` | `{"error": "invalid authorization token", "code": "invalid_api_key"}` | Key value is not recognised: mistyped, revoked, a publishable `pk_` key, or a key from the other environment's dashboard |
| `401` | `{"error": "invalid authorization token: this API key has expired …", "code": "api_key_expired"}` | An `sk_` key used after its `expiresAt` |
| `401` | `code` `key_environment_mismatch` | An `sk_test_` key on an account that has gone live (or the reverse) — issue a key of the account's current mode |
| `401` | `{"error": "invalid authorization token: invalid access token: …", "code": "invalid_token"}` | An OAuth access token that expired, whose connection was revoked, or presented outside the MCP endpoint |
| `401` | `{"error": "seller auth is required"}` | Missing seller context inside a handler |
| `403` | `{"error": "seller account is not active", "code": "account_not_active"}` | Key is valid but the seller account isn't active — new demo accounts activate automatically; if you see this, contact Fynex with your seller account ID |
| `403` | `{"error": "this API key is restricted: …", "code": "insufficient_scope"}` | A restricted `sk_` key without the permission this route needs — see [Restricted keys](#restricted-keys) |
| `403` | `{"error": "resource does not belong to this seller"}` | Key is valid but the resource belongs to a different seller |

> [!NOTE]
> Every error body is JSON. Branch on `code`, not on the `error` text — see [Errors](https://docs.fynex.ai/payments-api/v2/docs#tag/errors).

## See also

- **[Quickstart](https://docs.fynex.ai/payments-api/v2/docs#tag/quickstart)** — Take your first test payment in 5 minutes.
- **[Errors](https://docs.fynex.ai/payments-api/v2/docs#tag/errors)** — Full status code and error body reference.
- **[Request headers](https://docs.fynex.ai/payments-api/v2/docs#tag/headers)** — All request headers reference — required, conditional, and optional.
