Skip to content

Authentication ​

Securing your BITXpay API keys is critical. Exposed credentials can lead to compromised accounts and financial loss.

On this page ​

Overview ​

All currently published BITXpay APIs (Payments and Subscriptions) use a single authentication method for merchant-facing endpoints.

Signature Authentication (Ed25519 / EdDSA) ​

Merchant APIs
Payment links and other merchant-facing operations are authenticated with an Ed25519 (EdDSA) signature over a canonical message. RSA-PSS with SHA-256 is also accepted for legacy keys issued before Ed25519 was adopted.

Planned: HMAC-SHA256

An HMAC-SHA256 scheme is planned for a future set of standard (non-merchant) APIs. It has no live endpoints today and is not part of the current contract.

Security overview ​

Secret API keys must never appear in client side code or public repositories

These keys are for server side use only. If a secret key is exposed, delete it immediately from the dashboard and generate a new one.

Signature authentication (Ed25519) — merchant APIs ​

Getting your keys ​

  1. Log in to your BITXpay Dashboard
  2. Navigate to Developers → API Keys
  3. Generate your Merchant API Key and Private Key
  4. Store both securely — the private key is shown only once

Your credentials will include:

CredentialFormatExample
API Key (public identifier)btxm_ + 12 hex characters, same shape in sandbox and productionbtxm_9b451fa04a2e
Private Key (keep secret)Ed25519: + base64 of the PKCS#8 DER key (not PEM)Ed25519:MC4CAQAwBQYDK2VwBCIEI…
Public KeyEd25519: + base64 of the SubjectPublicKeyInfo DER keyEd25519:MCowBQYDK2VwAyEA…

Legacy accounts have an RSA key pair in PEM format instead. A key only works in the environment whose dashboard issued it.

Required headers ​

http
X-API-Key: btxm_9b451fa04a2e
X-API-Signature: <base64_encoded_ed25519_signature>
X-API-Timestamp: 2026-01-31T17:53:56Z
Content-Type: application/json

Generating the signature ​

The signature is created by signing the canonical message with your private key:

Message Format:

METHOD + PATH + TIMESTAMP + BODY

PATH is the full request path including /api/v1 (no host, no query string); BODY is the exact raw body string you send (empty for GET). There are no separators.

Sign the full path

Signing /payment_links while calling https://sandboxapi.bitxpay.com/api/v1/payment_links fails with SIGNATURE_VERIFICATION_FAILED. Sign /api/v1/payment_links.

Example Message:

POST/api/v1/payment_links2026-01-31T17:53:56Z{"amount":100.50,"currency":"USDT","payment_name":"Invoice #12345"}

Signature Parameters (Ed25519 — default):

  • Algorithm: Ed25519 (EdDSA)
  • Hashing: performed internally by Ed25519 (SHA-512) — do not pre-hash the message
  • Signature size: 64 bytes (fixed)
  • Output Format: raw signature bytes, base64-encoded for transmission

Legacy RSA-PSS keys: RSA-PSS with SHA-256, 2048-bit minimum, raw signature bytes base64-encoded.

Code examples ​

javascript
import crypto from 'crypto';

// Load the private key exactly as the dashboard issued it:
//   "Ed25519:<base64 PKCS#8 DER>"  (current keys)
//   "-----BEGIN PRIVATE KEY-----"  (legacy RSA keys, PEM)
function loadPrivateKey(raw) {
  raw = raw.trim();
  if (raw.startsWith('Ed25519:')) {
    return crypto.createPrivateKey({
      key: Buffer.from(raw.slice('Ed25519:'.length), 'base64'),
      format: 'der',
      type: 'pkcs8',
    });
  }
  return crypto.createPrivateKey(raw);
}

// message = METHOD + PATH + TIMESTAMP + BODY  (no separators)
// PATH is the full request path, including the /api/v1 prefix.
function sign(privateKey, method, path, timestamp, body = '') {
  const message = `${method}${path}${timestamp}${body}`;
  if (privateKey.asymmetricKeyType === 'ed25519') {
    // Ed25519 hashes internally: algorithm must be null, do not pre-hash.
    return crypto.sign(null, Buffer.from(message, 'utf8'), privateKey).toString('base64');
  }
  // Legacy RSA keys: RSA-PSS with SHA-256, salt length = digest length.
  return crypto
    .sign('sha256', Buffer.from(message, 'utf8'), {
      key: privateKey,
      padding: crypto.constants.RSA_PKCS1_PSS_PADDING,
      saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST,
    })
    .toString('base64');
}

// Usage
const apiKey = process.env.MERCHANT_API_KEY;               // btxm_xxxxxxxxxxxx
const privateKey = loadPrivateKey(process.env.MERCHANT_PRIVATE_KEY); // Ed25519:MC4CAQAw...

const host = 'https://sandboxapi.bitxpay.com';
const path = '/api/v1/payment_links';                       // sign the FULL path
const method = 'POST';
const timestamp = new Date().toISOString();                 // RFC 3339, UTC
const body = JSON.stringify({
  payment_name: 'Invoice #12345',
  amount: 100.5,
  currency: 'USDT',
  customer_email: 'john@example.com',
  success_url: 'https://example.com/success',
  cancel_url: 'https://example.com/cancel',
});

const signature = sign(privateKey, method, path, timestamp, body);

const response = await fetch(host + path, {
  method,
  headers: {
    'X-API-Key': apiKey,
    'X-API-Signature': signature,
    'X-API-Timestamp': timestamp,
    'Content-Type': 'application/json',
  },
  body, // send the exact string that was signed
});
console.log(response.status, await response.json());
python
import base64
import json
import os
from datetime import datetime, timezone

import requests
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ed25519, padding


def load_private_key(raw: str):
    """Load the key exactly as the dashboard issued it.

    "Ed25519:<base64 PKCS#8 DER>"   current keys
    "-----BEGIN PRIVATE KEY-----"   legacy RSA keys (PEM)
    """
    raw = raw.strip()
    if raw.startswith("Ed25519:"):
        der = base64.b64decode(raw[len("Ed25519:"):])
        return serialization.load_der_private_key(der, password=None)
    return serialization.load_pem_private_key(raw.encode(), password=None)


def sign(private_key, method: str, path: str, timestamp: str, body: str = "") -> str:
    # message = METHOD + PATH + TIMESTAMP + BODY (no separators)
    # PATH is the full request path, including the /api/v1 prefix.
    message = f"{method}{path}{timestamp}{body}".encode("utf-8")
    if isinstance(private_key, ed25519.Ed25519PrivateKey):
        signature = private_key.sign(message)  # Ed25519 hashes internally; do not pre-hash
    else:  # legacy RSA keys: RSA-PSS + SHA-256
        signature = private_key.sign(
            message,
            padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.DIGEST_LENGTH),
            hashes.SHA256(),
        )
    return base64.b64encode(signature).decode("ascii")


# Usage
api_key = os.environ["MERCHANT_API_KEY"]                       # btxm_xxxxxxxxxxxx
private_key = load_private_key(os.environ["MERCHANT_PRIVATE_KEY"])  # Ed25519:MC4CAQAw...

host = "https://sandboxapi.bitxpay.com"
path = "/api/v1/payment_links"                                  # sign the FULL path
method = "POST"
timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")  # RFC 3339, UTC
body = json.dumps({
    "payment_name": "Invoice #12345",
    "amount": 100.5,
    "currency": "USDT",
    "customer_email": "john@example.com",
    "success_url": "https://example.com/success",
    "cancel_url": "https://example.com/cancel",
})

signature = sign(private_key, method, path, timestamp, body)

response = requests.post(
    host + path,
    headers={
        "X-API-Key": api_key,
        "X-API-Signature": signature,
        "X-API-Timestamp": timestamp,
        "Content-Type": "application/json",
    },
    data=body,  # send the exact string that was signed (not json=...)
)
print(response.status_code, response.json())

Both samples load the dashboard-issued key and sign the exact request bytes. The private key is loaded straight from the Ed25519:… string the dashboard shows.

HMAC-SHA256 — planned ​

Not yet available

An HMAC-SHA256 authentication scheme is planned for a future set of standard (non-merchant) APIs. No live endpoints use it today, and it is not part of the current contract. Header names, message format, and code samples will be documented here once those endpoints ship. Until then, use the Ed25519 signature scheme above for all merchant-facing requests.

API key permissions ​

Key configuration supports scopes, expiry, and an optional domain restriction. Scope enforcement depends on each route's middleware; the mounted payment/subscription groups do not supply endpoint-specific required scopes. Do not assume a configured read scope prevents writes on these groups. Dashboard-only APIs also require a dashboard session; a merchant key does not grant access to every account operation.

Security best practices ​

1. Never embed keys in code ​

Embedding API keys in code increases the risk of accidental exposure. When sharing code, you might forget to remove embedded keys.

Instead: Store keys in environment variables or files outside your application's source tree.

2. Never store keys inside your source tree ​

Keep API key files outside your application's source tree to prevent them from being committed to version control systems like GitHub.

3. Restrict signatures to specific APIs ​

When multiple APIs are enabled in your project, restrict key usage to specific APIs to prevent replay attacks. Include the API request path in the signing body to ensure signatures work only for their intended API.

4. Delete unused keys ​

Remove API keys you no longer need to minimize the attack surface.

5. Rotate keys periodically ​

Regular key rotation reduces the risk of long-term key compromise. Since BITXpay Developer Platform uses asymmetric cryptography, key rotation requires creating new keys and deleting old ones.

Additional recommendations ​

  • Monitor API key usage for suspicious activity
  • Implement rate limiting on your endpoints
  • Use HTTPS for all API communications
  • Always validate SSL certificates when connecting over HTTPS
  • Log and audit API key usage
  • Have an incident response plan for compromised keys
  • Regularly review and update your security practices
  • Consider using hardware security modules (HSMs) or secure enclaves for key storage in production
  • Follow the principle of least privilege when granting API permissions
  • Use separate keys for development, testing, and production environments