# Payments API

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

---

## Create Payment

Create a new payment session:

+++ TypeScript
```typescript
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
```
+++

### 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 |
| `slug` | `string` | URL-friendly identifier |
| `checkoutUrl` | `string` | URL for customer checkout |

---

## Get Payment

Retrieve full payment details:

+++ TypeScript
```typescript
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):

+++ TypeScript
```typescript
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:

+++ TypeScript
```typescript
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:

+++ TypeScript
```typescript
// 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:

+++ TypeScript
```typescript
// 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;
  }
}
```
+++

---

## Type Definitions

### Payment

```typescript
interface Payment {
  id: string;
  merchantId: string;
  status: PaymentStatus;
  checkoutUrl: string;
  amount: {
    value: string;
    formatted: string;
    currency: 'HIVE' | 'HBD';
    usdCents: number;
  };
  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

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

---

## Examples

### E-commerce Checkout

+++ TypeScript
```typescript
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

+++ TypeScript
```typescript
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;
}
```
+++
