Skip to main content

API Examples (Node.js)

These examples use Node.js 18+ (built-in fetch, no extra packages needed). Copy the full script or individual functions into your project. Requirements:
  • Node.js 18+ (uses built-in fetch, no extra packages needed)
  • A valid Niftipay API key (generate one in Dashboard → Settings)

Configuration

// Your Niftipay API key — find it in Dashboard → Account → Settings
const API_KEY = "YOUR_API_KEY";

// Base URL of your Niftipay instance (no trailing slash)
const BASE_URL = "https://your-domain.com";

Helper: make an authenticated request

All examples below use this shared helper to make authenticated API calls:
async function apiRequest(method, path, body) {
  const url = `${BASE_URL}${path}`;

  const response = await fetch(url, {
    method,
    headers: {
      // Authenticate every request with your API key
      "x-api-key": API_KEY,
      // All request and response bodies are JSON
      "Content-Type": "application/json",
      Accept: "application/json",
    },
    body: body ? JSON.stringify(body) : undefined,
  });

  // Parse the JSON response
  const data = await response.json();

  // If the request failed, throw with the status and error details
  if (!response.ok) {
    throw new Error(
      `API ${response.status}: ${JSON.stringify(data, null, 2)}`
    );
  }

  return data;
}

Example 1: Create a Crypto Invoice Order

This creates a crypto payment invoice that your customer can pay directly from their wallet. Once the on-chain payment is detected, the order is marked “paid” and a webhook fires. Endpoint: POST /api/orders Flow:
  1. You call POST /api/orders with customer + amount details
  2. The API returns a deposit address, payment URI, and QR code
  3. You show the QR / URI to your customer
  4. Customer sends crypto to the deposit address
  5. Order status changes to “paid” → webhook fires
async function createCryptoOrder() {
  console.log("━━━ Example 1: Create Crypto Invoice Order ━━━\n");

  const order = await apiRequest("POST", "/api/orders", {
    // ── Required fields ──────────────────────────

    // Blockchain network to receive payment on
    // Accepted values: "BTC" | "LTC" | "ETH" | "SOL" | "XRP"
    network: "ETH",

    // Crypto asset the customer will pay with
    // Native coins: "BTC", "LTC", "ETH", "SOL", "XRP"
    // ERC-20 tokens (ETH network only): "USDT", "USDC"
    asset: "USDT",

    // Invoice amount in fiat (the amount you want to charge)
    // The API converts this to the equivalent crypto amount automatically
    amount: 50,

    // Customer details — used for tracking and email notifications
    firstName: "Jane",
    lastName: "Doe",
    email: "jane.doe@example.com",

    // ── Optional fields ──────────────────────────

    // Fiat currency for the invoice amount (defaults to "EUR")
    // This determines what currency the `amount` field is in
    currency: "EUR",

    // Your own unique reference for this order (e.g. your internal order ID)
    // If omitted, the API generates a UUID automatically
    // Must be unique per user — duplicates return a 409 conflict error
    reference: "MY-ORDER-001",
  });

  // ── Reading the response ──────────────────────

  console.log("Order created successfully!\n");

  // Unique order ID on Niftipay's side
  console.log("  Order ID:        ", order.order.id);

  // Your reference (or the auto-generated UUID)
  console.log("  Reference:       ", order.order.reference);

  // The blockchain deposit address — customer sends crypto here
  console.log("  Deposit address: ", order.order.address);

  // For XRP only: the destination tag the customer must include
  if (order.order.destinationTag) {
    console.log("  Destination tag: ", order.order.destinationTag);
  }

  // Total crypto amount the customer needs to send (amount + network fees)
  console.log("  Total to send:   ", order.order.totalToSend, order.order.asset);

  // A ready-to-use payment URI (e.g. "ethereum:<address>?amount=...")
  // You can embed this in a link or button so wallets open directly
  console.log("  Payment URI:     ", order.order.paymentUri);

  // URL to a QR code image — display this so the customer can scan & pay
  console.log("  QR code URL:     ", order.order.qrUrl);

  // Order status — starts as "pending", becomes "paid" after payment
  console.log("  Status:          ", order.order.status);

  // When the invoice expires (customer must pay before this time)
  console.log("  Expires at:      ", order.order.expiresAt);

  console.log();
  return order;
}
See also: Crypto Orders API reference

This creates a hosted checkout link where your customer can buy crypto with a credit card or bank transfer. The purchased crypto is sent to a Niftipay deposit address, and once detected on-chain, you receive the funds and a webhook fires. Endpoint: POST /api/ramping/links Flow:
  1. You call POST /api/ramping/links with customer + fiat amount
  2. The API returns a redirect URL (hosted checkout page)
  3. You redirect the customer to that URL
  4. Customer picks a payment method (card / bank), completes KYC if needed
  5. Provider purchases crypto and sends it to the deposit address
  6. Once on-chain deposit is detected, order is marked “paid” → webhook fires
async function createOnrampingOrder() {
  console.log("━━━ Example 2: Create Onramping Pay-Link ━━━\n");

  const result = await apiRequest("POST", "/api/ramping/links", {
    // ── Required fields ──────────────────────────

    // Customer details — used for the checkout flow and KYC verification
    firstName: "John",
    lastName: "Smith",
    email: "john.smith@example.com",

    // The net fiat amount you (the merchant) want to receive
    // The onramp provider may add its own fees on top for the customer
    fiatAmount: 100,

    // ── Optional fields ──────────────────────────

    // Blockchain network for the crypto purchase
    // Accepted values: "BTC" | "LTC" | "ETH" | "SOL" | "XRP"
    // If omitted, falls back to your saved default in dashboard settings
    network: "ETH",

    // Crypto asset to purchase
    // Native coins: "BTC", "LTC", "ETH", "SOL", "XRP"
    // ERC-20 tokens (ETH network only): "USDT", "USDC"
    // If omitted, falls back to your saved default in dashboard settings
    asset: "USDT",

    // Fiat currency the customer will pay in (defaults to "EUR")
    // Supported: USD, EUR, GBP, AUD, AED, BRL, CAD, CHF, CZK, DKK,
    //            HKD, IDR, INR, JPY, MXN, NOK, NZD, PHP, PLN, QAR,
    //            RON, SAR, SEK, SGD, THB, TRY, TWD, VND, ZAR
    fiatCurrency: "EUR",

    // Your own unique reference for this order
    // If omitted, the API generates one automatically
    reference: "RAMP-ORDER-001",

    // Optional: preferred onramp provider
    // If omitted, the API auto-selects the best provider based on
    // the customer's geolocation
    // provider: "banxa",
  });

  // ── Reading the response ──────────────────────

  console.log("Onramping pay-link created successfully!\n");

  // *** This is the most important field ***
  // Redirect your customer to this URL to start the checkout
  console.log("  Checkout URL:    ", result.url);

  // The signed token embedded in the URL (for verification)
  console.log("  Token:           ", result.token);

  console.log("\n  ── Underlying crypto invoice ──");

  // The crypto invoice created behind the scenes
  console.log("  Order ID:        ", result.order.id);
  console.log("  Reference:       ", result.order.reference);
  console.log("  Deposit address: ", result.order.depositAddress);
  console.log("  Crypto amount:   ", result.order.amountCrypto, result.order.asset);
  console.log("  Fiat amount:     ", result.order.fiatAmount, result.order.fiatCurrency);
  console.log("  Status:          ", result.order.status);
  console.log("  Expires at:      ", result.order.expiresAt);

  console.log("\n  ── Pay-link details ──");

  // Additional details about the pay-link and fee breakdown
  console.log("  Fiat (net):      ", result.link.fiatAmountNet);
  console.log("  Fiat (gross):    ", result.link.fiatAmountGross);
  console.log("  Fee percent:     ", result.link.feePercent);
  console.log("  Provider hint:   ", result.link.providerHint || "auto-selected");
  console.log("  Link expires at: ", result.link.expiresAt);

  console.log();
  return result;
}
See also: Onramping API reference

Example 3: Create a Fiat Payment Order

This creates a fiat payment order (card / bank transfer) using one of your configured fiat integrations. The API returns a hosted payment URL where the customer completes the payment. Endpoint: POST /api/fiat/orders Prerequisites:
  • Fiat payments must be enabled on your account
  • You need a fiat Integration ID (find it in Dashboard → Settings → Fiat)
Flow:
  1. You call POST /api/fiat/orders with integration, amount, and currency
  2. The API returns a payment URL and QR code
  3. You redirect the customer to the payment URL (or show the QR code)
  4. Customer pays via card or bank transfer on the hosted page
  5. Order status changes to “completed” → webhook fires
async function createFiatOrder() {
  console.log("━━━ Example 3: Create Fiat Payment Order ━━━\n");

  const result = await apiRequest("POST", "/api/fiat/orders", {
    // ── Required fields ──────────────────────────

    // Your fiat integration ID — find it in Dashboard → Settings → Fiat
    integrationId: "YOUR_INTEGRATION_ID",

    // Fiat currency for the payment (ISO 4217 code)
    // Supported: EUR, USD, GBP, AUD, AED, BRL, CAD, CHF, CZK, DKK,
    //            HKD, IDR, INR, JPY, MXN, NOK, NZD, PHP, PLN, QAR,
    //            RON, SAR, SEK, SGD, THB, TRY, TWD, VND, ZAR
    currency: "EUR",

    // ── Amount (provide ONE of the following) ────

    // Option A: Amount in major units (e.g. 19.95 means €19.95)
    amount: 19.95,

    // Option B: Amount in minor units / cents (e.g. 1995 means €19.95)
    // amountCents: 1995,

    // ── Optional fields ──────────────────────────

    // A short description shown on the payment page
    description: "Widget purchase",

    // Your own unique reference for this order (max 80 characters)
    // If omitted, the API generates one automatically
    // Must be unique per user — duplicates return a 409 conflict error
    reference: "FIAT-ORDER-001",

    // Who pays the service/processing fee: "customer" or "merchant"
    // If omitted, falls back to your default setting in dashboard
    serviceFeePayer: "customer",

    // Customer email — used for receipts and CRM tracking
    email: "jane.doe@example.com",
  });

  // ── Reading the response ──────────────────────

  console.log("Fiat order created successfully!\n");

  // *** This is the most important field ***
  // Redirect your customer to this URL to complete the payment
  console.log("  Payment URL:     ", result.order.payUrl);

  // Unique order ID on Niftipay's side
  console.log("  Order ID:        ", result.order.id);

  // Your reference (or the auto-generated one)
  console.log("  Reference:       ", result.reference);

  // Order status — starts as "new", becomes "completed" after payment
  console.log("  Status:          ", result.order.status);

  // QR code URL — display so the customer can scan to open the payment page
  console.log("  QR code URL:     ", result.qrUrl);

  console.log("\n  ── Pricing breakdown ──");

  // The subtotal (your requested amount)
  console.log("  Subtotal:        ", result.display.subtotal, result.display.currency);

  // The service/processing fee
  console.log("  Service fee:     ", result.display.serviceFee, result.display.currency);

  // The total the customer will be charged (if customer pays fee)
  // or the total you receive after deduction (if merchant pays fee)
  console.log("  Total:           ", result.display.total, result.display.currency);

  // Who is paying the fee
  console.log("  Fee paid by:     ", result.pricing.payer);

  // Detailed fee breakdown
  if (result.pricing.serviceFeeBreakdown) {
    console.log("  Fee percent:     ", result.pricing.serviceFeeBreakdown.totalPercent + "%");
  }

  // When the order expires (12 hours from creation)
  console.log("  Expires at:      ", result.expiresAt);

  console.log();
  return result;
}
See also: Fiat Orders API reference

Run all examples

async function main() {
  try {
    await createCryptoOrder();
    await createOnrampingOrder();
    await createFiatOrder();

    console.log("All examples completed successfully.");
  } catch (error) {
    console.error("Error:", error.message);
    process.exit(1);
  }
}

main();
To run:
  1. Replace YOUR_API_KEY and https://your-domain.com with your real values
  2. Save the full script as api-examples.mjs
  3. Run: node api-examples.mjs