> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ledig.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Authentication

> Use your API key and secret to sign requests from your server.

Use your business API key and secret to authenticate requests. Your server calculates an HMAC-SHA256 signature for each request, so Ledig can verify that it came from you and has not changed.

Some endpoints also accept a bearer token, as shown in the API reference. Use one authentication method per request. Sending both a bearer token and an API key returns `401`.

## Credentials and permissions

| Value | How to use it |
| - | - |
| API key | Send in `x-ledig-key`. Keep it in server-side configuration. |
| Secret | Use it to calculate the signature. Never send it as a header. |
| API URL | Use `https://api-sandbox.ledig.io` for Sandbox or `https://api.ledig.io` for Live. |

Your business administrator creates API keys in the dashboard. A business can have up to ten active keys, each expiring within six months. Save the secret when creating or rotating a key; it is shown only once. Rotation replaces the old secret immediately, and revocation stops the key from working.

Keep credentials in a server-side secret manager. Do not put them in browser or mobile code, repositories, URLs or logs.

| Permission type | Access |
| - | - |
| Full access (`api:*`) | All API operations available to your business. |
| Read only (`api:read`) | Read requests and `POST /v1/payouts/fee-estimate`. Other POST requests are not included. |
| Custom | The individual scopes assigned to the key. |

Each endpoint lists its required scope, which is the permission your key needs. Payments still need to meet your business's service access, recipient approval, balance and limit requirements.

## HMAC v1

Use v1 for requests on behalf of your own business. Send these three headers:

| Header | Value |
| - | - |
| `x-ledig-key` | Your API key |
| `x-ledig-timestamp` | Current Unix time in seconds, as a ten-digit string |
| `x-ledig-signature` | `v1=` followed by the base64 HMAC-SHA256 digest |

Build this exact UTF-8 string:

```text theme={null}
{timestamp}.{METHOD}.{pathWithQuery}.{rawBody}
```

Use the uppercase method. Include the exact path and query string, beginning with `/`; do not include the scheme or hostname. For a request without a body, use the empty string. For JSON, serialize once, then sign and send that same string. Whitespace, query ordering and JSON key ordering affect the signature.

Calculate the digest with your secret and standard base64 encoding. Timestamps must be within 300 seconds of server time. Keep your server clock in sync and use a fresh timestamp and signature for every attempt.

## Examples

Set `LEDIG_API_BASE_URL` to `https://api-sandbox.ledig.io` to start in Sandbox. Load `LEDIG_API_KEY` and `LEDIG_API_SECRET` from your server's secret configuration.

These examples read your USD balance. The signature and timestamp are calculated for the request; they are not API keys.

```js Node.js theme={null}
import { createHmac } from "node:crypto";

const { LEDIG_API_BASE_URL, LEDIG_API_KEY, LEDIG_API_SECRET } = process.env;
if (!LEDIG_API_BASE_URL || !LEDIG_API_KEY || !LEDIG_API_SECRET) {
  throw new Error(
    "Set the three LEDIG_API configuration values before running.",
  );
}
const origin = new URL(LEDIG_API_BASE_URL);
if (
  origin.protocol !== "https:" ||
  origin.pathname !== "/" ||
  origin.search ||
  origin.hash ||
  origin.username ||
  origin.password
) {
  throw new Error(
    "LEDIG_API_BASE_URL must be an HTTPS origin without a path or credentials.",
  );
}

function sign(method, pathWithQuery, rawBody = "") {
  const timestamp = Math.floor(Date.now() / 1000).toString();
  const payload = `${timestamp}.${method.toUpperCase()}.${pathWithQuery}.${rawBody}`;
  const signature = `v1=${createHmac("sha256", LEDIG_API_SECRET).update(payload, "utf8").digest("base64")}`;
  return { timestamp, signature };
}

const path = "/v1/balances/USD";
const { timestamp, signature } = sign("GET", path);
const response = await fetch(`${origin.origin}${path}`, {
  headers: {
    "x-ledig-key": LEDIG_API_KEY,
    "x-ledig-timestamp": timestamp,
    "x-ledig-signature": signature,
  },
});
const result = await response.json(); // Use this response within your application.
console.log({
  httpStatus: response.status,
  requestId: response.headers.get("x-request-id"),
});
```

```python Python theme={null}
import base64
import hashlib
import hmac
import json
import os
import time
import urllib.error
import urllib.parse
import urllib.request

base_url = os.environ["LEDIG_API_BASE_URL"].rstrip("/")
api_key = os.environ["LEDIG_API_KEY"]
secret = os.environ["LEDIG_API_SECRET"]
origin = urllib.parse.urlsplit(base_url)
if (origin.scheme != "https" or not origin.hostname or origin.path
        or origin.query or origin.fragment or origin.username or origin.password):
    raise ValueError("LEDIG_API_BASE_URL must be an HTTPS origin without a path or credentials.")

def sign(method, path_with_query, raw_body=""):
    timestamp = str(int(time.time()))
    payload = f"{timestamp}.{method.upper()}.{path_with_query}.{raw_body}"
    digest = hmac.new(secret.encode("utf-8"), payload.encode("utf-8"), hashlib.sha256).digest()
    return timestamp, "v1=" + base64.b64encode(digest).decode("ascii")

path = "/v1/balances/USD"
timestamp, signature = sign("GET", path)
request = urllib.request.Request(base_url + path, headers={
    "x-ledig-key": api_key,
    "x-ledig-timestamp": timestamp,
    "x-ledig-signature": signature,
})
try:
    response = urllib.request.urlopen(request)
except urllib.error.HTTPError as error:
    response = error
with response:
    result = json.load(response)  # Use this response within your application.
    print({"httpStatus": response.status, "requestId": response.headers.get("x-request-id")})
```

For a JSON request, serialize the body once and sign that exact text. Send the same text with `Content-Type: application/json`. If the response is lost, follow the [retry rules](https://docs.ledig.io/guides/idempotency.md).

## Act for a managed business

Use HMAC v2 when your institution makes payments or reads balances for a business it manages. V2 includes the business-selection headers in the signature.

| Header | What to send |
| - | - |
| `X-Ledig-Business-Id` | The ID of the business you are acting for. |
| `X-Ledig-Acting-Business-Id` | Optional. If included, use your institution's ID, which owns the API key. |
| `X-Ledig-Profile-Id` | Usually omitted. If your integration uses it, it must match the selected business. |

Build the v2 payload using compact JSON, in this exact order. This Node.js helper uses the `createHmac` import from the example above:

```js theme={null}
function signV2(
  secret,
  timestamp,
  method,
  pathWithQuery,
  rawBody,
  selection = {},
) {
  const payload = JSON.stringify([
    "ledig-hmac-v2",
    timestamp,
    method.toUpperCase(),
    pathWithQuery,
    rawBody,
    selection.businessId?.trim() ?? "",
    selection.profileId?.trim() ?? "",
    selection.actingBusinessId?.trim() ?? "",
  ]);
  return `v2=${createHmac("sha256", secret).update(payload, "utf8").digest("base64")}`;
}
```

The last three values must match the headers you send, with surrounding whitespace trimmed. Use `""` for an omitted header. IDs are case-sensitive. Send the resulting signature in `x-ledig-signature`, along with the key and timestamp headers.

V1 cannot select a managed business. Your institution must have access to that business, and your key must have the permissions required for the request.

> [!NOTE]
>
> When onboarding a managed business, keep your institution selected and put
> the managed business ID in the endpoint path. You can use v1 or v2 for these
> requests. See [Managed businesses](https://docs.ledig.io/guides/managed-businesses.md).

## Troubleshooting

If authentication fails, check your server clock, uppercase method, query string, body text and selected business. The values you sign must match the request you send.

Save the request ID and HTTP status when troubleshooting. Do not log secrets, signatures or the full signing text, which can contain customer information.

See [Errors and troubleshooting](https://docs.ledig.io/errors/errors-and-troubleshooting.md) for response codes and safe retries.


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