# JavaScript SDK

### Requirements

* Node.js 18+ (uses native `fetch`)

### Installation

```bash
npm install otpgan-sdk
```

### Quick Start

```js
import { OtpganClient } from 'otpgan-sdk';

const client = new OtpganClient({
  apiKey: 'otpk_live_xxxxxxxxxxxxxxxx',
});

// Get account balance
const account = await client.getAccount();
console.log(account.balance);

// Create OTP order
const order = await client.createOrder({ service: 'wa' });
console.log(order.phoneNumber);

// Wait for OTP (polls automatically)
const result = await client.waitForOtp(order.orderId);
console.log(result.otpCode);

// Finish order
await client.finishOrder(order.orderId);
```

### API Reference

#### `new OtpganClient(options)`

| Option    | Type   | Required | Description                                            |
| --------- | ------ | -------- | ------------------------------------------------------ |
| `apiKey`  | string | Yes      | Your OTPGAN API key                                    |
| `baseUrl` | string | No       | Custom base URL (default: `https://otpgan.com/api/v1`) |

***

#### `client.getAccount()`

Returns account email and balance.

```js
const { email, balance } = await client.getAccount();
```

***

#### `client.getOperators()`

Returns available mobile operators.

```js
const { country, operators } = await client.getOperators();
// operators: ['AXIS', 'TSEL', 'ISAT', 'XL', 'TRI']
```

***

#### `client.getServices()`

Returns all active services with pricing (IDR).

```js
const services = await client.getServices();
// [{ id, name, slug, category, price, iconUrl }]
```

***

#### `client.createOrder(options)`

Creates a new OTP order. Deducts balance immediately.

| Option     | Type   | Required | Description                     |
| ---------- | ------ | -------- | ------------------------------- |
| `service`  | string | Yes      | Service slug (e.g. `wa`, `tg`)  |
| `operator` | string | No       | Operator name (default: Random) |

```js
const order = await client.createOrder({
  service: 'wa',
  operator: 'TSEL',
});
// { orderId, phoneNumber, operator, service, price, expiresAt }
```

***

#### `client.getOrderStatus(orderId)`

Check order status and OTP code.

```js
const status = await client.getOrderStatus('order-uuid');
// { orderId, phoneNumber, otpCode, status, operator, service, ... }
```

**Statuses:** `pending` | `received` | `completed` | `expired` | `cancelled`

***

#### `client.cancelOrder(orderId)`

Cancel a pending order (refunds balance).

```js
const result = await client.cancelOrder('order-uuid');
// { orderId, action: 'cancel', message: '...' }
```

***

#### `client.finishOrder(orderId)`

Finish a received order.

```js
const result = await client.finishOrder('order-uuid');
// { orderId, action: 'finish', message: '...' }
```

***

#### `client.waitForOtp(orderId, options?)`

Polls `getOrderStatus` until OTP is received or timeout.

| Option     | Type   | Default | Description                 |
| ---------- | ------ | ------- | --------------------------- |
| `interval` | number | 3000    | Polling interval in ms      |
| `timeout`  | number | 300000  | Max wait time in ms (5 min) |

```js
const result = await client.waitForOtp('order-uuid', {
  interval: 3000,
  timeout: 300000,
});
console.log(result.otpCode);
```

***

### Error Handling

The SDK throws typed errors for different failure scenarios:

```js
import { OtpganClient, AuthError, RateLimitError, ValidationError } from 'otpgan-sdk';

try {
  await client.createOrder({ service: 'wa' });
} catch (error) {
  if (error instanceof AuthError) {
    // Invalid API key (401)
  } else if (error instanceof RateLimitError) {
    // Too many requests (429)
  } else if (error instanceof ValidationError) {
    // Bad request (400)
  }
}
```

| Error Class       | HTTP Code | Description                |
| ----------------- | --------- | -------------------------- |
| `OtpganError`     | —         | Base error class           |
| `AuthError`       | 401       | Invalid or missing API key |
| `RateLimitError`  | 429       | Rate limit exceeded        |
| `NotFoundError`   | 404       | Resource not found         |
| `ValidationError` | 400       | Invalid request parameters |

### License

MIT


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://otpgan.gitbook.io/overview/sdk/javascript-sdk.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
