Skip to content

Quick Start ​

Get started with BITXpay in minutes. This guide will walk you through creating your first payment integration.

Prerequisites ​

Before you begin, ensure you have:

  • A BITXpay merchant account (Sign up here)
  • API credentials (API Key and Ed25519 private key)
  • Basic knowledge of REST APIs
  • A development environment with Node.js, Python, or your preferred language

Step 1: Get your API credentials ​

  1. Log in to your BITXpay Dashboard
  2. Navigate to Developers → API Keys
  3. Click Create API Key
  4. Save your API Key (btxm_xxxxxxxxxxxx) and private key (Ed25519:…, shown only once) securely

Keep your credentials safe

Never commit API keys or private keys to version control or expose them in client-side code.

Step 2: Make your first API call ​

Test your credentials by fetching the currencies your payment links can use. Every request is signed over METHOD + PATH + TIMESTAMP + BODY, where PATH is the full path including /api/v1 and the private key is loaded straight from the Ed25519:… string the dashboard gave you.

javascript
import crypto from 'crypto';

const apiKey = process.env.MERCHANT_API_KEY;              // btxm_xxxxxxxxxxxx
const raw = process.env.MERCHANT_PRIVATE_KEY;             // Ed25519:MC4CAQAw...
const privateKey = crypto.createPrivateKey({
  key: Buffer.from(raw.slice('Ed25519:'.length), 'base64'),
  format: 'der',
  type: 'pkcs8',
});

const host = 'https://sandboxapi.bitxpay.com';
const path = '/api/v1/payment_links/currencies';          // full path is signed
const timestamp = new Date().toISOString();
const message = `GET${path}${timestamp}`;                 // no body for GET
const signature = crypto.sign(null, Buffer.from(message, 'utf8'), privateKey).toString('base64');

const res = await fetch(host + path, {
  headers: {
    'X-API-Key': apiKey,
    'X-API-Signature': signature,
    'X-API-Timestamp': timestamp,
    'Accept': 'application/json',
  },
});
console.log(res.status, await res.json());
python
import base64, os
from datetime import datetime, timezone
import requests
from cryptography.hazmat.primitives import serialization

api_key = os.environ["MERCHANT_API_KEY"]                    # btxm_xxxxxxxxxxxx
raw = os.environ["MERCHANT_PRIVATE_KEY"]                    # Ed25519:MC4CAQAw...
private_key = serialization.load_der_private_key(
    base64.b64decode(raw[len("Ed25519:"):]), password=None
)

host = "https://sandboxapi.bitxpay.com"
path = "/api/v1/payment_links/currencies"                   # full path is signed
timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
message = f"GET{path}{timestamp}"                           # no body for GET
signature = base64.b64encode(private_key.sign(message.encode())).decode()

res = requests.get(host + path, headers={
    "X-API-Key": api_key,
    "X-API-Signature": signature,
    "X-API-Timestamp": timestamp,
    "Accept": "application/json",
})
print(res.status_code, res.json())

A 200 with {"message": "Currencies retrieved successfully", "data": [...]} means your key and signing are correct. A 401 with code: "SIGNATURE_VERIFICATION_FAILED" almost always means the signed path is missing the /api/v1 prefix.

Step 3: Create a payment ​

Create your first payment request:

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())

The response is 201 Created with the link in data; the customer-facing checkout URL is data.payment_url. The URL comes from the deployment configuration; add https:// only if it has no scheme. New links start in payment_status: "processing".

Step 4: Handle webhooks ​

Configure a webhook URL and secret in your dashboard, then verify X-Webhook-Signature: sha256=<hex> over the raw request body. Route events using event_type, for example payment.succeeded.

javascript
import crypto from 'node:crypto';
import express from 'express';

const app = express();
const secret = process.env.WEBHOOK_SECRET;
if (!secret) throw new Error('WEBHOOK_SECRET is required');

export function verifyWebhook(rawBody, signature, webhookSecret) {
  if (typeof signature !== 'string' || !/^sha256=[a-f0-9]{64}$/.test(signature)) {
    return false;
  }
  const expected = crypto.createHmac('sha256', webhookSecret).update(rawBody).digest();
  return crypto.timingSafeEqual(Buffer.from(signature.slice(7), 'hex'), expected);
}

// Register before express.json() middleware to preserve the signed bytes.
app.post('/webhook', express.raw({ type: 'application/json' }), async (req, res) => {
  if (!verifyWebhook(req.body, req.headers['x-webhook-signature'], secret)) {
    return res.status(401).send('Invalid signature');
  }
  const event = JSON.parse(req.body.toString('utf8'));
  console.log('Webhook:', event.event_type, event.data);
  // Durably enqueue the verified event before acknowledging it.
  // Apply business changes idempotently using payment/transaction references
  // in event.data: delivery id changes on retry; event_id identifies a type.
  res.sendStatus(200);
});

app.listen(3000);
python
import hashlib
import hmac
import json
import os

from flask import Flask, request

app = Flask(__name__)
secret = os.environ['WEBHOOK_SECRET']


def verify_webhook(raw_body: bytes, signature: str, webhook_secret: str) -> bool:
    expected = 'sha256=' + hmac.new(
        webhook_secret.encode('utf-8'), raw_body, hashlib.sha256
    ).hexdigest()
    return hmac.compare_digest(signature.encode('utf-8'), expected.encode('ascii'))


@app.post('/webhook')
def webhook():
    raw_body = request.get_data()
    signature = request.headers.get('X-Webhook-Signature', '')
    if not verify_webhook(raw_body, signature, secret):
        return 'Invalid signature', 401
    event = json.loads(raw_body)
    app.logger.info('Webhook: %s', event['event_type'])
    # Durably enqueue before acknowledging. Deduplicate business changes using
    # payment/transaction references in event['data'], not the delivery id.
    return 'OK', 200


if __name__ == '__main__':
    app.run(port=3000)

See Webhooks for signatures, retries, and duplicate handling, and Webhook Event Data for exact payload fields. In engine payment events, data.payment_id identifies the payment link; data.link_id is its display reference.

Step 5: Test in sandbox ​

BITXpay provides a sandbox environment for testing:

Use sandbox credentials for development. For engine-backed checkout, explicitly set is_test: true to request a simulated order; choosing the sandbox host alone does not set test mode.

Next steps ​

Now that you've created your first payment, explore more features:

Common issues ​

Invalid signature error ​

Make sure you're:

  • Using the correct Ed25519 private key
  • Including the timestamp in the signature (ISO 8601 format)
  • Formatting the message string correctly: ${method}${path}${timestamp}${body} — e.g. POST/api/v1/payment_links2026-01-31T12:00:00Z{...}
  • Signing with Ed25519 over METHOD + /api/v1/... + TIMESTAMP + BODY (do not pre-hash — Ed25519 hashes internally)
  • Encoding the final signature as Base64

Webhook not receiving events ​

Verify that:

  • Your webhook URL is publicly accessible
  • You're returning a 200 status code
  • Your server supports HTTPS (required for production)

Payment not completing ​

Check that:

  • The merchant amount is a JSON number greater than zero
  • The currency is supported
  • The redirect URL is valid

For more troubleshooting help, see our Troubleshooting Guide.