# Authentication & Request Signing

> Sign API requests with HMAC-SHA256 using your project UUID and API key.

Every API request (except incoming webhooks) must carry your project UUID and a request signature. The signature proves the request came from you and that nobody changed it on the way.

## API keys

2328.io uses **two keys** that share the same signing algorithm but cover different endpoints:

| Key | Used for |
|-----|----------|
| **API key** | Payments, static wallets, balance, exchange rates, and verification of payment / static-wallet webhooks |
| **Payout API key** | All `/v1/payout/*` endpoints and verification of payout webhooks |

Both keys live in your project settings on [2328.io](https://2328.io). Examples below say "API key" generically — substitute the right one for the endpoint you're calling.

> **INFO:** **Never** mix the two keys: signing a payout request with the regular API key (or a payment request with the payout key) returns a signature error.

## Required headers

| Header | Type | Required | Description |
|--------|------|----------|-------------|
| `Content-Type` | string | yes | Always `application/json` |
| `project` | string | yes | Your project UUID |
| `sign` | string | yes | HMAC-SHA256 signature of the request, computed with your API key |
| `User-Agent` | string | yes | Identifies your application (e.g. `MyShop/1.4 (+https://myshop.example)`). Requests without a `User-Agent` may be blocked. |

## How the signature works

Think of the signature as a fingerprint of the request body. It is built by:

1. Serializing the body to JSON (compact — no extra whitespace).
2. Base64-encoding that JSON. This step normalises the input across languages — once it's plain ASCII, every language produces the same bytes for HMAC.
3. Computing **HMAC-SHA256** of the Base64 string using your API key, then converting the result to lowercase hex.

For **GET** and other request types without a body, sign an empty string instead of the JSON.

> **INFO:** The empty-string signature is constant for a given API key. You can cache it if you make many GET calls.

## Implementations

#### php

```php
<?php
function apiSign(array $data, string $apiKey): string {
    $json = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    $base64 = base64_encode($json);
    return hash_hmac('sha256', $base64, $apiKey);
}
```

#### js

```js
import crypto from "crypto";

export function apiSign(data, apiKey) {
  const json = JSON.stringify(data);
  const base64 = Buffer.from(json).toString("base64");
  return crypto.createHmac("sha256", apiKey).update(base64).digest("hex");
}
```

#### ts

```ts
import { createHmac } from "crypto";

export function apiSign(data: object, apiKey: string): string {
  const json = JSON.stringify(data);
  const base64 = Buffer.from(json).toString("base64");
  return createHmac("sha256", apiKey).update(base64).digest("hex");
}
```

#### python

```python
import json
import hmac
import hashlib
import base64

def api_sign(data: dict, api_key: str) -> str:
    # ensure_ascii=False keeps non-ASCII characters (Cyrillic, Chinese, …)
    # as-is. Without it, Python escapes them to \uXXXX and the signature
    # diverges from PHP / Node / Go.
    body = json.dumps(data, separators=(",", ":"), ensure_ascii=False)
    b64 = base64.b64encode(body.encode("utf-8")).decode()
    return hmac.new(api_key.encode(), b64.encode(), hashlib.sha256).hexdigest()
```

#### go

```go
package sign

import (
    "bytes"
    "crypto/hmac"
    "crypto/sha256"
    "encoding/base64"
    "encoding/hex"
    "encoding/json"
)

func ApiSign(data any, apiKey string) (string, error) {
    // json.Encoder with SetEscapeHTML(false) — without it, Go escapes <, >, &
    // to \u003c etc., which breaks compatibility with PHP / Node / Python.
    var buf bytes.Buffer
    enc := json.NewEncoder(&buf)
    enc.SetEscapeHTML(false)
    if err := enc.Encode(data); err != nil {
        return "", err
    }
    // Encoder appends a trailing newline — drop it.
    body := bytes.TrimRight(buf.Bytes(), "\n")

    b64 := base64.StdEncoding.EncodeToString(body)
    h := hmac.New(sha256.New, []byte(apiKey))
    h.Write([]byte(b64))
    return hex.EncodeToString(h.Sum(nil)), nil
}
```

### Bodyless requests (GET)

For empty-body requests (e.g. `GET /v1/payout/status/{uuid}`), sign an empty string. Since `base64_encode('')` is also empty, the HMAC input is just `""`:

#### curl

```curl
SIGN=$(printf '' | openssl dgst -sha256 -hmac "$API_KEY" -hex | awk '{print $NF}')
```

#### php

```php
$sign = hash_hmac('sha256', base64_encode(''), $apiKey);
```

#### js

```js
import { createHmac } from "crypto";

const sign = createHmac("sha256", apiKey)
  .update(Buffer.from("").toString("base64"))
  .digest("hex");
```

#### ts

```ts
import { createHmac } from "crypto";

const sign: string = createHmac("sha256", apiKey)
  .update(Buffer.from("").toString("base64"))
  .digest("hex");
```

#### python

```python
import hmac
import hashlib
import base64

sign = hmac.new(
    api_key.encode(),
    base64.b64encode(b"").decode().encode(),
    hashlib.sha256,
).hexdigest()
```

#### go

```go
package sign

import (
    "crypto/hmac"
    "crypto/sha256"
    "encoding/base64"
    "encoding/hex"
)

func EmptyBodySign(apiKey string) string {
    b64 := base64.StdEncoding.EncodeToString([]byte(""))
    h := hmac.New(sha256.New, []byte(apiKey))
    h.Write([]byte(b64))
    return hex.EncodeToString(h.Sum(nil))
}
```

## Full request example

#### curl

```curl
curl -X POST https://api.2328.io/api/v1/payment \
  -H "Content-Type: application/json" \
  -H "User-Agent: MyShop/1.0 (+https://myshop.example)" \
  -H "project: YOUR_PROJECT_UUID" \
  -H "sign: YOUR_HMAC_SIGNATURE" \
  -d '{"amount":"100.00","currency":"USD","order_id":"ORDER-123"}'
```

#### php

```php
<?php
function apiSign(string $body, string $apiKey): string {
    return hash_hmac('sha256', base64_encode($body), $apiKey);
}

$project = 'YOUR_PROJECT_UUID';
$apiKey  = 'YOUR_API_KEY';

$data = [
    'amount'   => '100.00',
    'currency' => 'USD',
    'order_id' => 'ORDER-123',
];

$body = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$sign = apiSign($body, $apiKey);

$ch = curl_init('https://api.2328.io/api/v1/payment');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $body,
    CURLOPT_HTTPHEADER => [
        'Content-Type: application/json',
        'User-Agent: MyShop/1.0 (+https://myshop.example)',
        "project: $project",
        "sign: $sign",
    ],
]);

$response = json_decode(curl_exec($ch), true);
```

#### js

```js
import { createHmac } from "crypto";

function apiSign(body, apiKey) {
  const base64 = Buffer.from(body, "utf8").toString("base64");
  return createHmac("sha256", apiKey).update(base64).digest("hex");
}

const data = {
  amount: "100.00",
  currency: "USD",
  order_id: "ORDER-123",
};

const body = JSON.stringify(data);
const sign = apiSign(body, process.env.API_KEY);

const res = await fetch("https://api.2328.io/api/v1/payment", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "User-Agent": "MyShop/1.0 (+https://myshop.example)",
    project: process.env.PROJECT_UUID,
    sign,
  },
  body,
});

const json = await res.json();
```

#### ts

```ts
import { createHmac } from "crypto";

function apiSign(body: string, apiKey: string): string {
  const base64 = Buffer.from(body, "utf8").toString("base64");
  return createHmac("sha256", apiKey).update(base64).digest("hex");
}

type CreatePaymentBody = {
  amount: string;
  currency: string;
  order_id: string;
};

type CreatePaymentResponse = { state: number; result: unknown };

const data: CreatePaymentBody = {
  amount: "100.00",
  currency: "USD",
  order_id: "ORDER-123",
};

const body = JSON.stringify(data);
const sign = apiSign(body, process.env.API_KEY!);

const res = await fetch("https://api.2328.io/api/v1/payment", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "User-Agent": "MyShop/1.0 (+https://myshop.example)",
    project: process.env.PROJECT_UUID!,
    sign,
  },
  body,
});

const json = (await res.json()) as CreatePaymentResponse;
```

#### python

```python
import json
import hmac
import hashlib
import base64
import httpx

def api_sign(body: str, api_key: str) -> str:
    b64 = base64.b64encode(body.encode("utf-8")).decode()
    return hmac.new(api_key.encode(), b64.encode(), hashlib.sha256).hexdigest()

data = {
    "amount": "100.00",
    "currency": "USD",
    "order_id": "ORDER-123",
}

body = json.dumps(data, separators=(",", ":"), ensure_ascii=False)
sign = api_sign(body, API_KEY)

r = httpx.post(
    "https://api.2328.io/api/v1/payment",
    headers={
        "Content-Type": "application/json",
        "User-Agent": "MyShop/1.0 (+https://myshop.example)",
        "project": PROJECT_UUID,
        "sign": sign,
    },
    content=body.encode("utf-8"),
)
response = r.json()
```

#### go

```go
package main

import (
    "bytes"
    "crypto/hmac"
    "crypto/sha256"
    "encoding/base64"
    "encoding/hex"
    "encoding/json"
    "net/http"
)

func ApiSign(body []byte, apiKey string) string {
    b64 := base64.StdEncoding.EncodeToString(body)
    h := hmac.New(sha256.New, []byte(apiKey))
    h.Write([]byte(b64))
    return hex.EncodeToString(h.Sum(nil))
}

func marshalCanonical(v any) ([]byte, error) {
    var buf bytes.Buffer
    enc := json.NewEncoder(&buf)
    enc.SetEscapeHTML(false)
    if err := enc.Encode(v); err != nil {
        return nil, err
    }
    return bytes.TrimRight(buf.Bytes(), "\n"), nil
}

func main() {
    data := struct {
        Amount   string `json:"amount"`
        Currency string `json:"currency"`
        OrderID  string `json:"order_id"`
    }{
        Amount:   "100.00",
        Currency: "USD",
        OrderID:  "ORDER-123",
    }

    body, err := marshalCanonical(data)
    if err != nil {
        panic(err)
    }
    sign := ApiSign(body, apiKey)

    req, _ := http.NewRequest("POST",
        "https://api.2328.io/api/v1/payment",
        bytes.NewReader(body))
    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("User-Agent", "MyShop/1.0 (+https://myshop.example)")
    req.Header.Set("project", projectUUID)
    req.Header.Set("sign", sign)

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()
}
```

> **DANGER:** **Never expose your API key in client-side code.** Sign requests on your backend. A leaked API key gives anyone full access to your merchant account.

## Verifying webhook signatures

When 2328.io sends you a webhook, the same algorithm runs in reverse:

1. Pull the `sign` field out of the payload.
2. JSON-encode the remaining fields (compact, no whitespace).
3. Base64-encode that string.
4. Compute `HMAC-SHA256` with the appropriate key.
5. Compare it with the received `sign` using a **constant-time** comparison (`hash_equals`, `crypto.timingSafeEqual`, `hmac.compare_digest`, `subtle.ConstantTimeCompare`, `OpenSSL.fixed_length_secure_compare`).

The signing key depends on the webhook source:

| Webhook | Key to verify with |
|---------|---------------------|
| Payment / static-wallet webhooks (`/v1/payment`, `/v1/static-wallet`) | **API key** |
| Payout webhooks (`/v1/payout`) | **Payout API key** |

> **WARNING:** **Common verification pitfalls.** Your JSON encoder must produce the **exact same bytes** the sender produced — otherwise the Base64 differs and the signature won't match.
> 
> - **Go**: use `json.NewEncoder` with `SetEscapeHTML(false)`. The default `json.Marshal` escapes `<`, `>`, `&` to `<` and breaks the signature.
> - **Python**: pass `ensure_ascii=False` to `json.dumps`. Without it, non-ASCII (Cyrillic, Chinese, …) is escaped to `\uXXXX`.
> - **Compact JSON**: no whitespace between fields (`separators=(",", ":")` in Python).
> - **Field order** (Go): a plain `map[string]any` randomises keys on re-encode. Use `json.RawMessage`, an ordered struct, or strip `sign` from the raw bytes.
> 
> If verification keeps failing, run `apiSign` on the payload yourself — it must produce the same hex string as the received `sign`.

> **INFO:** **A valid signature does not prevent replays.** It only proves the webhook came from 2328.io — it doesn't stop an attacker from re-posting a *captured* webhook later. Always check idempotency by `uuid` (or `txid` for static wallets) before crediting funds. Reject with HTTP `401` if the signature is missing or wrong.

Full code examples live on **[Webhook Notifications](/docs/webhooks#verifying-the-signature)**. Retry handling and idempotency rules are in [Best practices](/docs/webhooks#best-practices).