# Authentication & signing

Every OnCharge API request is signed on your server with your store's API secret. OnCharge never accepts a bare API key, and the secret never travels over the network.

> **Server-side only.** Never put your API secret in browser code, a mobile app, a public repository or a client-side environment variable (anything prefixed `NEXT_PUBLIC_`, `VITE_`, `REACT_APP_` and so on). The browser only ever receives the checkout URL.

## Your credentials

| Credential | Looks like | Where it is used |
|---|---|---|
| API key | `oc_key_…` | Sent in the `X-Oncharge-Key` header. Identifies your store. |
| API secret | `oc_sec_…` | Never sent. Used to compute the request signature. |
| Webhook signing secret | `oc_cbsec_…` | Verifies webhooks OnCharge sends you. See [Webhooks](https://oncharge.io/docs/webhooks). |
| Store ID | a UUID | Only the WooCommerce plugin asks for it. |

Generate API credentials for a store on the **Stores** page of the merchant portal at [app.oncharge.io](https://app.oncharge.io). The secret is shown **once**; store it in your secret manager or server environment, for example:

```bash title=".env (server only)"
ONCHARGE_API_KEY=oc_key_...
ONCHARGE_API_SECRET=oc_sec_...
ONCHARGE_BASE_URL=https://app.oncharge.io
```

**New stores.** A store's keys are issued when it is approved, but the store stays `pending` until OnCharge has opened its processing account. Until it is active, every request with its keys fails with `403 store_inactive`; keep the keys and retry later, nothing needs to be regenerated.

**Rotating keys.** Rotating a store's keys in the portal issues a new key and secret and keeps the old pair working for a 14-day grace window, so you can deploy the new pair without downtime. Regenerating keys instead revokes every old key immediately; use that if a secret leaked.

## Base URL

```text
https://app.oncharge.io
```

All endpoints live under `/api/v1/`. See the [API reference](https://oncharge.io/docs/api) or download the [OpenAPI 3.1 spec](https://oncharge.io/openapi.json).

## How to sign a request

Each request carries three headers:

| Header | Value |
|---|---|
| `X-Oncharge-Key` | Your API key. |
| `X-Oncharge-Timestamp` | The current Unix time in seconds, e.g. `1767225600`. |
| `X-Oncharge-Signature` | The signature computed below, lower-case hex. |

Compute the signature in four steps:

1. **Body hash.** `body_hash = hex(sha256(raw_body))`, where `raw_body` is the exact bytes you send. For `GET` requests and for `POST` requests without a body, hash the empty string (`e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855`).
2. **Signing string.** `signing_string = "{timestamp}.{METHOD}.{path}.{body_hash}"`. `{timestamp}` is the exact string you put in `X-Oncharge-Timestamp`; `{METHOD}` is upper case; `{path}` is the URL path **without the query string**, for example `/api/v1/shipments` for `GET /api/v1/shipments?session_id=…`.
3. **Signing key.** `signing_key = hex(sha256(api_secret))`: the 64-character lower-case hex digest of your API secret, used as an ASCII string. Do not decode it back to bytes.
4. **Signature.** `X-Oncharge-Signature = hex(hmac_sha256(signing_key, signing_string))`.

OnCharge rejects a request when the timestamp is more than **300 seconds** away from its clock, so keep your server's clock synced (NTP).

> **Serialize once.** Hash and send the same string. If you sign `JSON.stringify(body)` and then let your HTTP client serialize the object again, whitespace or key order can differ and the signature will not match.

### Test vector

Use this to check your implementation without calling the API:

| Input | Value |
|---|---|
| API secret | `oc_sec_example_secret_do_not_use` |
| Timestamp | `1767225600` |
| Method and path | `POST /api/v1/checkout/sessions` |
| Body | `{"amount":4900,"currency":"USD","reference":"order-1001","return_url":"https://shop.example.com/thanks"}` |
| Body hash | `5e52ceb9b1f344953c18661d556985d8cc6da177161aae0192a494cad909077b` |
| Signing key | `da99cc22bdd7ff7663935ccc2966a363e9b0fe1c4fc4b9803c7469ef2de84d54` |
| Signing string | `1767225600.POST./api/v1/checkout/sessions.5e52ceb9b1f344953c18661d556985d8cc6da177161aae0192a494cad909077b` |
| Signature | `7b0e1f9370475ae2a926804c0c9927c5f391c8a3c2e09a8071d98891aa01fdc7` |

A `GET /api/v1/shipments?session_id=…` with the same secret and timestamp signs `1767225600.GET./api/v1/shipments.e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855` and gives `e03651b9e5bf9da64bacc56efcc7e0c11471e2942fede23c61141434528c4a6f`.

## Examples

Each example reads `ONCHARGE_API_KEY`, `ONCHARGE_API_SECRET` and (optionally) `ONCHARGE_BASE_URL` from the environment, creates a checkout session and then reads the order's delivery status with a query-string request. They use only each language's standard library, and each one has been run against a reimplementation of OnCharge's server-side signature check.

### curl

```bash title="oncharge.sh" test="sign-curl"
#!/usr/bin/env bash
# Usage: oncharge METHOD PATH [JSON_BODY]
set -euo pipefail

oncharge() {
  local method="$1" path="$2" body="${3:-}"
  local base="${ONCHARGE_BASE_URL:-https://app.oncharge.io}"
  local ts body_hash signing_key signature
  ts="$(date +%s)"
  body_hash="$(printf '%s' "$body" | openssl dgst -sha256 -hex | awk '{print $NF}')"
  signing_key="$(printf '%s' "$ONCHARGE_API_SECRET" | openssl dgst -sha256 -hex | awk '{print $NF}')"
  # Sign the path without the query string.
  signature="$(printf '%s' "$ts.$method.${path%%\?*}.$body_hash" \
    | openssl dgst -sha256 -hmac "$signing_key" -hex | awk '{print $NF}')"

  local args=(-sS -X "$method" "$base$path"
    -H "Content-Type: application/json"
    -H "X-Oncharge-Key: $ONCHARGE_API_KEY"
    -H "X-Oncharge-Timestamp: $ts"
    -H "X-Oncharge-Signature: $signature")
  if [ -n "$body" ]; then args+=(--data-raw "$body"); fi
  curl "${args[@]}"
}

oncharge POST /api/v1/checkout/sessions \
  '{"amount":4900,"currency":"USD","reference":"order-1001","return_url":"https://shop.example.com/thanks"}'
echo
oncharge GET "/api/v1/shipments?session_id=8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11"
echo
```

### Node.js

Node 18 or later (uses the built-in `fetch`). With the [Node SDK](https://oncharge.io/docs/sdks) you do not need this code.

```js title="oncharge.mjs" test="sign-node"
import { createHash, createHmac } from 'node:crypto';

const BASE_URL = process.env.ONCHARGE_BASE_URL ?? 'https://app.oncharge.io';
const sha256Hex = (value) => createHash('sha256').update(value, 'utf8').digest('hex');

export async function onchargeRequest(method, path, body, { idempotencyKey } = {}) {
  const rawBody = body === undefined ? '' : JSON.stringify(body);
  const timestamp = Math.floor(Date.now() / 1000).toString();
  const url = new URL(path, BASE_URL);
  // Sign the path without the query string.
  const signingString = `${timestamp}.${method.toUpperCase()}.${url.pathname}.${sha256Hex(rawBody)}`;
  const signature = createHmac('sha256', sha256Hex(process.env.ONCHARGE_API_SECRET))
    .update(signingString, 'utf8')
    .digest('hex');

  const res = await fetch(url, {
    method,
    headers: {
      'Content-Type': 'application/json',
      'X-Oncharge-Key': process.env.ONCHARGE_API_KEY,
      'X-Oncharge-Timestamp': timestamp,
      'X-Oncharge-Signature': signature,
      ...(idempotencyKey ? { 'Idempotency-Key': idempotencyKey } : {}),
    },
    body: rawBody === '' ? undefined : rawBody, // send exactly the bytes you hashed
  });
  const data = await res.json();
  if (!res.ok) {
    throw Object.assign(new Error(data.message ?? `HTTP ${res.status}`), { status: res.status, code: data.error });
  }
  return data;
}

const session = await onchargeRequest(
  'POST',
  '/api/v1/checkout/sessions',
  { amount: 4900, currency: 'USD', reference: 'order-1001', return_url: 'https://shop.example.com/thanks' },
  { idempotencyKey: 'order-1001' },
);
console.log(session.session_id, new URL(session.iframe_url, BASE_URL).href);

const delivery = await onchargeRequest('GET', `/api/v1/shipments?session_id=${session.session_id}`);
console.log(delivery.delivery.state);
```

### PHP

PHP 7.4 or later with the `curl` extension.

```php title="oncharge.php" test="sign-php"
<?php
function oncharge_request(string $method, string $path, ?array $body = null, ?string $idempotencyKey = null): array
{
    $baseUrl = getenv('ONCHARGE_BASE_URL') ?: 'https://app.oncharge.io';
    $rawBody = $body === null ? '' : json_encode($body, JSON_UNESCAPED_SLASHES);
    $timestamp = (string) time();
    // Sign the path without the query string.
    $pathOnly = parse_url($path, PHP_URL_PATH);
    $signingString = $timestamp . '.' . strtoupper($method) . '.' . $pathOnly . '.' . hash('sha256', $rawBody);
    $signature = hash_hmac('sha256', $signingString, hash('sha256', getenv('ONCHARGE_API_SECRET')));

    $headers = [
        'Content-Type: application/json',
        'X-Oncharge-Key: ' . getenv('ONCHARGE_API_KEY'),
        'X-Oncharge-Timestamp: ' . $timestamp,
        'X-Oncharge-Signature: ' . $signature,
    ];
    if ($idempotencyKey !== null) {
        $headers[] = 'Idempotency-Key: ' . $idempotencyKey;
    }

    $ch = curl_init($baseUrl . $path);
    curl_setopt_array($ch, [
        CURLOPT_CUSTOMREQUEST => strtoupper($method),
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 30,
    ]);
    if ($rawBody !== '') {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $rawBody); // send exactly the bytes you hashed
    }
    $response = curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($response === false) {
        throw new RuntimeException('OnCharge request failed: ' . curl_error($ch));
    }

    $data = json_decode($response, true) ?? [];
    if ($status >= 400) {
        throw new RuntimeException(($data['error'] ?? 'http_error') . ': ' . ($data['message'] ?? "HTTP $status"));
    }
    return $data;
}

$session = oncharge_request('POST', '/api/v1/checkout/sessions', [
    'amount' => 4900,
    'currency' => 'USD',
    'reference' => 'order-1001',
    'return_url' => 'https://shop.example.com/thanks',
], 'order-1001');
echo $session['session_id'], ' ', $session['iframe_url'], PHP_EOL;

$delivery = oncharge_request('GET', '/api/v1/shipments?session_id=' . urlencode($session['session_id']));
echo $delivery['delivery']['state'], PHP_EOL;
```

### Python

Python 3.8 or later, standard library only.

```python title="oncharge.py" test="sign-python"
import hashlib
import hmac
import json
import os
import time
import urllib.error
import urllib.request
from urllib.parse import urlsplit

BASE_URL = os.environ.get("ONCHARGE_BASE_URL", "https://app.oncharge.io")


def oncharge_request(method, path, body=None, idempotency_key=None):
    raw_body = "" if body is None else json.dumps(body, separators=(",", ":"))
    timestamp = str(int(time.time()))
    # Sign the path without the query string.
    body_hash = hashlib.sha256(raw_body.encode("utf-8")).hexdigest()
    signing_string = f"{timestamp}.{method.upper()}.{urlsplit(path).path}.{body_hash}"
    signing_key = hashlib.sha256(os.environ["ONCHARGE_API_SECRET"].encode("utf-8")).hexdigest()
    signature = hmac.new(signing_key.encode("ascii"), signing_string.encode("utf-8"), hashlib.sha256).hexdigest()

    headers = {
        "Content-Type": "application/json",
        "User-Agent": "my-store/1.0",
        "X-Oncharge-Key": os.environ["ONCHARGE_API_KEY"],
        "X-Oncharge-Timestamp": timestamp,
        "X-Oncharge-Signature": signature,
    }
    if idempotency_key:
        headers["Idempotency-Key"] = idempotency_key

    request = urllib.request.Request(
        BASE_URL + path,
        data=raw_body.encode("utf-8") if raw_body else None,  # send exactly the bytes you hashed
        headers=headers,
        method=method.upper(),
    )
    try:
        with urllib.request.urlopen(request, timeout=30) as response:
            return json.loads(response.read())
    except urllib.error.HTTPError as err:
        payload = json.loads(err.read() or b"{}")
        raise RuntimeError(f"{payload.get('error')}: {payload.get('message')}") from None


session = oncharge_request(
    "POST",
    "/api/v1/checkout/sessions",
    {"amount": 4900, "currency": "USD", "reference": "order-1001", "return_url": "https://shop.example.com/thanks"},
    idempotency_key="order-1001",
)
print(session["session_id"], session["iframe_url"])

delivery = oncharge_request("GET", f"/api/v1/shipments?session_id={session['session_id']}")
print(delivery["delivery"]["state"])
```

## Idempotency

Send an `Idempotency-Key` header on requests that create something, so a retry after a timeout cannot create it twice:

- **`POST /api/v1/checkout/sessions`**: while a session created with the same key is still open (`created` or `pending`) and less than 50 minutes old, OnCharge returns that session (HTTP 200) instead of creating a new one. Use your order or cart ID.
- **`POST /api/v1/refunds`**: a repeat with the same key returns the first refund with `"idempotent": true`. Use your refund ID.
- **`POST /api/v1/checkout/sessions/{id}/cancel`**: the key is passed along so a retried cancellation is not applied twice.

The key is part of the headers, not the signature.

## Store domains

Register every domain your store runs on (for example `shop.example.com` and `www.shop.example.com`) for the store under **Security → Domains** in the merchant portal. OnCharge uses the list three ways:

- `return_url` must be on a registered domain, or session creation fails with `invalid_return_url`.
- The checkout may only be framed by pages on a registered domain (over HTTPS; a registered `localhost` works from any port).
- If an API request carries an `Origin`, `Referer` or `X-Store-Domain` header, at least one must match a registered domain, or it fails with `domain_mismatch`. Server-to-server calls normally send none of these; you may send `X-Store-Domain: shop.example.com` to make the origin explicit.

## Rate limits

Requests are rate-limited per store. A limited request gets `429 rate_limited` with `X-RateLimit-Limit`, `X-RateLimit-Remaining` and `X-RateLimit-Reset` (Unix seconds) headers. Wait until the reset time, then retry with the same `Idempotency-Key`.

## Errors

Errors are JSON with a stable `error` code and a human-readable `message`:

```json
{ "error": "invalid_signature", "message": "HMAC signature verification failed" }
```

| Status | `error` | What to check |
|---|---|---|
| 401 | `missing_auth` | All three `X-Oncharge-*` headers are present. |
| 401 | `invalid_timestamp` | The timestamp is an integer number of seconds (not milliseconds). |
| 401 | `timestamp_expired` | Your server clock is within 300 seconds of real time. |
| 401 | `invalid_key` | The API key is correct and has not been revoked or rotated out. |
| 401 | `invalid_signature` | Signing key is `sha256(secret)` as hex text; path has no query string; body hash is of the exact bytes sent; method is upper case; timestamp string matches the header. |
| 403 | `store_inactive` | The store is active in the portal. A newly approved store is `pending` until OnCharge has opened its processing account, and its keys are refused until then; a suspended store is refused too. |
| 403 | `store_checkout_closed` | Only on session creation: OnCharge has closed the store to new payments (for example while the account is being offboarded). Shipments, refunds and other calls still work. |
| 403 | `domain_mismatch` | `Origin`/`Referer`/`X-Store-Domain` is a registered store domain. |
| 429 | `rate_limited` | Back off until `X-RateLimit-Reset`. |
| 503 | `service_unavailable`, `config_error` | Temporary. Retry with backoff. |

Each endpoint's own errors are listed in the [API reference](https://oncharge.io/docs/api).
