# Payments API

Create, retrieve, and manage payment sessions using the SDK.


# Create Payment

Create a new payment session:

const payment = await hivepay.payments.create({
  amount: '10500',           // Amount in satoshis
  currency: 'HBD',           // 'HIVE' or 'HBD'
  description: 'Order #123', // Shown to customer
  redirectUrl: 'https://yoursite.com/success',  // Optional
  cancelUrl: 'https://yoursite.com/cancel',     // Optional
  metadata: { orderId: '12345' }                // Optional
});

console.log(payment.id);          // Payment ID
console.log(payment.checkoutUrl); // Checkout URL
console.log(payment.status);      // 'pending'
console.log(payment.fee);         // Fee amount
console.log(payment.net);         // Net amount

# Parameters

Parameter Type Required Description
amount string Yes Amount in satoshis (smallest unit)
currency 'HIVE' \| 'HBD' Yes Payment currency
description string Yes Description shown to customer
redirectUrl string No URL after successful payment
cancelUrl string No URL after cancelled payment
metadata object No Custom data to attach

# Response

Field Type Description
id string Unique payment ID
status PaymentStatus Current status
checkoutUrl string URL for customer checkout
amount AmountDetails Amount information
fee string Fee in satoshis
net string Net amount in satoshis
expiresAt Date Expiration timestamp
createdAt Date Creation timestamp

# Get Payment

Retrieve full payment details:

const payment = await hivepay.payments.get('payment_id');

console.log(payment.status);           // Current status
console.log(payment.amount.formatted); // '10.500 HBD'
console.log(payment.amount.usdCents);  // USD equivalent
console.log(payment.completedAt);      // Date or null
console.log(payment.metadata);         // Your custom data

# Get Status

Quick status check (lighter response):

const status = await hivepay.payments.getStatus('payment_id');

if (status === 'completed') {
  // Handle success
} else if (status === 'pending') {
  // Still waiting
}

# Status Values

Status Description
pending Awaiting customer action
processing Payment in progress
completed Successfully completed
failed Payment failed
user_cancelled Customer cancelled
system_cancelled System cancelled/expired

# Wait for Completion

Poll until payment reaches terminal status:

try {
  const status = await hivepay.payments.waitFor('payment_id', {
    timeout: 300000,   // 5 minutes
    interval: 3000     // Check every 3 seconds
  });

  switch (status) {
    case 'completed':
      console.log('Payment successful!');
      break;
    case 'failed':
      console.log('Payment failed');
      break;
    case 'user_cancelled':
    case 'system_cancelled':
      console.log('Payment cancelled');
      break;
  }
} catch (error) {
  // Timeout exceeded
  console.error('Polling timed out');
}

# Options

Option Type Default Description
timeout number 300000 Max wait time (ms)
interval number 3000 Poll interval (ms)

# List Payments

Get paginated list of payments:

// First page with defaults
const result = await hivepay.payments.list();

console.log(result.data);                  // Payment[]
console.log(result.pagination.page);       // 1
console.log(result.pagination.limit);      // 20
console.log(result.pagination.total);      // Total count
console.log(result.pagination.totalPages); // Total pages

// Custom pagination
const page3 = await hivepay.payments.list({
  page: 3,
  limit: 50  // Max: 100
});

# Parameters

Parameter Type Default Description
page number 1 Page number
limit number 20 Items per page (max 100)

# Iterate Payments

Async iterator for processing all payments:

// Direct iteration
for await (const payment of hivepay.payments) {
  console.log(payment.id, payment.status);
}

// With custom page size
for await (const payment of hivepay.payments.iterate({ pageSize: 50 })) {
  await processPayment(payment);
}

// Early exit
for await (const payment of hivepay.payments) {
  if (payment.id === 'target_id') {
    console.log('Found!');
    break;
  }
}

# Get Fee Rate

Retrieve current fee percentage:

const feePercent = await hivepay.payments.getFeeRate();
console.log(`Fee: ${feePercent}%`); // e.g., "1.5%"

# Type Definitions

# Payment

interface Payment {
  id: string;
  merchantId: string;
  status: PaymentStatus;
  checkoutUrl: string;
  amount: {
    value: string;
    formatted: string;
    currency: 'HIVE' | 'HBD';
    usdCents: number;
  };
  fee: string;
  net: string;
  description: string;
  metadata?: Record<string, unknown>;
  redirectUrl?: string;
  cancelUrl?: string;
  expiresAt: Date;
  completedAt: Date | null;
  createdAt: Date;
}

type PaymentStatus =
  | 'pending'
  | 'processing'
  | 'completed'
  | 'failed'
  | 'user_cancelled'
  | 'system_cancelled';

# PaginatedResult

interface PaginatedResult<T> {
  data: T[];
  pagination: {
    page: number;
    limit: number;
    total: number;
    totalPages: number;
  };
}

# Examples

# E-commerce Checkout

async function createCheckout(cart: Cart) {
  const payment = await hivepay.payments.create({
    amount: cart.totalSatoshis.toString(),
    currency: 'HBD',
    description: `Order ${cart.id}`,
    redirectUrl: `https://store.com/orders/${cart.id}/success`,
    cancelUrl: `https://store.com/cart`,
    metadata: {
      orderId: cart.id,
      customerId: cart.customerId,
      items: cart.items.map(i => i.id)
    }
  });

  return payment.checkoutUrl;
}

# Payment Verification

async function verifyPayment(paymentId: string) {
  const payment = await hivepay.payments.get(paymentId);

  if (payment.status !== 'completed') {
    throw new Error(`Payment not completed: ${payment.status}`);
  }

  // Verify amount matches expected
  const expectedAmount = '10500';
  if (payment.amount.value !== expectedAmount) {
    throw new Error('Amount mismatch');
  }

  return payment;
}