> ## Documentation Index
> Fetch the complete documentation index at: https://docs.rampnow.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Rampnow SDK

> JavaScript/TypeScript SDK for embedding the Rampnow onramp and offramp widget into any website or web app

<Note>
  The Rampnow SDK provides a developer-friendly wrapper around the widget integration, with full TypeScript support, event handling, and a React hook.
</Note>

## Overview

The `@rampnow/sdk` package lets you embed Rampnow's onramp/offramp widget into your application with just a few lines of code. It supports three integration modes and ships with TypeScript definitions out of the box.

<div style={{display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1rem'}}>
  <Card title="Overlay Mode" icon="layer-group">
    Full-screen modal overlay — quickest setup, no container needed
  </Card>

  <Card title="Embedded Mode" icon="window">
    Mount the widget inside any DOM element in your layout
  </Card>

  <Card title="Redirect Mode" icon="arrow-up-right-from-square">
    Generate a URL to open in a new tab — ideal for native apps or email links
  </Card>

  <Card title="React Hook" icon="react">
    First-class React support via `useRampnowSdk`
  </Card>
</div>

<Tip>
  Try the SDK live at [demo.rampnow.io](https://demo.rampnow.io/).
</Tip>

***

## Installation

<CodeGroup>
  ```bash npm theme={null}
  npm install @rampnow/sdk
  ```

  ```bash yarn theme={null}
  yarn add @rampnow/sdk
  ```

  ```bash pnpm theme={null}
  pnpm add @rampnow/sdk
  ```
</CodeGroup>

**CDN (no bundler):**

```html theme={null}
<script src="https://cdn.jsdelivr.net/npm/@rampnow/sdk/dist/rampnow-sdk.umd.js"></script>
```

When loaded via CDN, the SDK is available as `window.RampnowSdk`.

***

## Quick Start

<Steps>
  <Step title="Get your API key">
    Obtain your public API key from the [Rampnow Partner Dashboard](https://partner.rampnow.io) under **API Hub**. Keys are prefixed with `pk_live_...`.
  </Step>

  <Step title="Initialize the SDK">
    ```javascript theme={null}
    import { RampnowSdk, RampnowEventType } from '@rampnow/sdk'

    const sdk = new RampnowSdk({
      apiKey: 'pk_live_YOUR_API_KEY',
      orderType: 'buy',
      srcCurrency: 'EUR',
      dstCurrency: 'ETH',
      dstChain: 'ethereum',
    })
    ```
  </Step>

  <Step title="Open the widget">
    ```javascript theme={null}
    sdk.init()
    ```
  </Step>

  <Step title="Listen for events">
    ```javascript theme={null}
    sdk.on(RampnowEventType.ORDER_COMPLETED, (e) => {
      console.log('Order completed:', e.payload.orderUid)
    })
    ```
  </Step>
</Steps>

***

## Configuration

Pass a config object when creating a new `RampnowSdk` instance:

| Option             | Type               | Default                  | Description                                        |
| ------------------ | ------------------ | ------------------------ | -------------------------------------------------- |
| `apiKey`           | `string`           | **required**             | Partner public API key                             |
| `widgetUrl`        | `string`           | `https://app.rampnow.io` | Override the widget base URL                       |
| `containerId`      | `string`           | —                        | DOM element ID for embedded mode; omit for overlay |
| `width`            | `string \| number` | `450`                    | Iframe width (px)                                  |
| `height`           | `string \| number` | `700`                    | Iframe height (px)                                 |
| `orderType`        | `'buy' \| 'sell'`  | —                        | Pre-select order direction                         |
| `srcCurrency`      | `string`           | —                        | Source currency, e.g. `'EUR'`, `'USD'`             |
| `srcChain`         | `string`           | —                        | Source chain                                       |
| `dstCurrency`      | `string`           | —                        | Destination currency, e.g. `'ETH'`, `'BTC'`        |
| `dstChain`         | `string`           | —                        | Destination chain, e.g. `'ethereum'`, `'bitcoin'`  |
| `paymentMode`      | `string`           | —                        | Payment method, e.g. `'SEPA'`, `'ACH'`             |
| `srcAmount`        | `string`           | —                        | Pre-fill source amount                             |
| `walletAddress`    | `string`           | —                        | Pre-fill recipient wallet address                  |
| `walletAddressTag` | `string`           | —                        | Wallet memo/tag (for XRP, XLM, etc.)               |
| `externalOrderId`  | `string`           | —                        | Your own order ID for cross-referencing            |
| `utm_source`       | `string`           | —                        | UTM tracking                                       |
| `utm_medium`       | `string`           | —                        | UTM tracking                                       |
| `utm_campaign`     | `string`           | —                        | UTM tracking                                       |

***

## Integration Modes

### Overlay Mode (Default)

Opens the widget as a full-screen modal overlay. No container element needed.

```javascript theme={null}
import { RampnowSdk } from '@rampnow/sdk'

const sdk = new RampnowSdk({
  apiKey: 'pk_live_YOUR_API_KEY',
  orderType: 'buy',
  srcCurrency: 'EUR',
  dstCurrency: 'ETH',
  dstChain: 'ethereum',
})

sdk.init() // Opens the overlay
```

### Embedded Mode

Mount the widget inside a specific DOM element by providing a `containerId`.

```html theme={null}
<div id="rampnow-widget"></div>
```

```javascript theme={null}
import { RampnowSdk } from '@rampnow/sdk'

const sdk = new RampnowSdk({
  apiKey: 'pk_live_YOUR_API_KEY',
  containerId: 'rampnow-widget',
  width: 450,
  height: 700,
  orderType: 'buy',
  dstCurrency: 'ETH',
  dstChain: 'ethereum',
})

sdk.init()
```

### Redirect Mode

Generate a widget URL without opening an iframe — useful for native apps, email links, or server-side flows.

```javascript theme={null}
import { RampnowSdk } from '@rampnow/sdk'

const url = RampnowSdk.createRedirectUrl({
  apiKey: 'pk_live_YOUR_API_KEY',
  orderType: 'buy',
  srcCurrency: 'EUR',
  srcAmount: '250',
  dstCurrency: 'BTC',
  dstChain: 'bitcoin',
  walletAddress: '0xYourWalletAddress',
})

window.open(url, '_blank')
```

***

## React Integration

The SDK ships with a React hook for seamless integration in React applications.

<Info>
  React (`>=18`) and ReactDOM (`>=18`) are optional peer dependencies — only required when using the hook.
</Info>

```tsx theme={null}
import { useRampnowSdk } from '@rampnow/sdk/react'
import { RampnowCommandType, RampnowEventType } from '@rampnow/sdk'
import { useEffect } from 'react'

function BuyCryptoButton() {
  const { init, close, send, on, isOpen } = useRampnowSdk({
    apiKey: 'pk_live_YOUR_API_KEY',
    srcCurrency: 'EUR',
    dstCurrency: 'ETH',
  })

  useEffect(() => {
    on(RampnowEventType.ORDER_COMPLETED, (e) => {
      console.log('Completed:', e.payload.orderUid)
      close()
    })
  }, [on, close])

  return <button onClick={init}>{isOpen ? 'Loading…' : 'Buy Crypto'}</button>
}
```

***

## API Reference

### `new RampnowSdk(config)`

Creates an SDK instance. Validates the `apiKey` and merges defaults. Does **not** open the widget — call `.init()` to display it.

### `sdk.init(): RampnowSdk`

Opens the widget. If `containerId` is set, mounts the iframe in that element; otherwise creates a full-screen overlay. Returns `this` for chaining.

### `sdk.close(): void`

Closes and removes the widget from the DOM.

### `sdk.on(eventType, callback): RampnowSdk`

Subscribe to widget events. Returns `this` for chaining.

```javascript theme={null}
// Single event
sdk.on(RampnowEventType.ORDER_CREATED, callback)

// Multiple events
sdk.on([RampnowEventType.ORDER_CREATED, RampnowEventType.ORDER_COMPLETED], callback)

// All events
sdk.on('*', callback)
```

### `sdk.off(eventType, callback): RampnowSdk`

Unsubscribe from events. Same forms as `.on()`.

### `sdk.send(commandType, payload): RampnowSdk`

Send a command to the widget iframe. Returns `this` for chaining. See [Commands](#commands) for available command types.

```javascript theme={null}
import { RampnowCommandType } from '@rampnow/sdk'

sdk.send(RampnowCommandType.UPDATE_PAYMENT_DETAIL, {
  transactionHash: '0xabc123...',
})
```

### `sdk.isOpen: boolean`

Read-only property indicating whether the widget is currently displayed.

### `RampnowSdk.createRedirectUrl(config): string` (static)

Builds a full widget URL from config without opening any iframe. Returns a URL string.

***

## Events

Subscribe to events using `sdk.on()` with the `RampnowEventType` enum:

| Event                      | Payload                                                                                                                                                    | Description                        |
| -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------- |
| `WIDGET_READY`             | —                                                                                                                                                          | Widget iframe loaded and ready     |
| `WIDGET_CLOSED`            | —                                                                                                                                                          | Widget was closed                  |
| `USER_AUTHENTICATED`       | —                                                                                                                                                          | User signed in                     |
| `ORDER_CREATED`            | `orderUid`, `orderType`, `srcCurrency`, `srcChain`, `srcAmount`, `dstCurrency`, `dstChain`, `paymentMode`, `cryptoTxnInfo?`, `bankTxnInfo?`                | Order successfully created         |
| `ORDER_PAYMENT_PROCESSING` | `orderUid`, `status`, `paymentStatus`                                                                                                                      | Payment is being processed         |
| `ORDER_PAYMENT_COMPLETED`  | `orderUid`, `status`, `paymentStatus`                                                                                                                      | Payment received by Rampnow        |
| `ORDER_PAYMENT_FAILED`     | `orderUid`, `status`, `paymentStatus`                                                                                                                      | Payment failed                     |
| `ORDER_COMPLETED`          | `orderUid`, `status`, `srcCurrency`, `srcChain`, `srcAmount`, `dstCurrency`, `dstChain`, `dstAmount`, `walletAddress`, `transactionHash`, `cryptoTxnInfo?` | Order fully completed, crypto sent |
| `ORDER_FAILED`             | `orderUid`, `status`                                                                                                                                       | Order failed or cancelled          |
| `ERROR`                    | `message`, `code?`                                                                                                                                         | Error occurred in the widget       |

### `CryptoTxnInfo`

Available in `ORDER_CREATED` and `ORDER_COMPLETED` event payloads:

| Field             | Type     | Description                                                     |
| ----------------- | -------- | --------------------------------------------------------------- |
| `currency`        | `string` | Crypto currency code, e.g. `"USDC"`                             |
| `chain`           | `string` | Chain code, e.g. `"ethereum"`                                   |
| `amount`          | `string` | Amount credited to the receiver                                 |
| `receiverAddress` | `string` | Address that received the crypto                                |
| `fillAmount`      | `string` | Filled/settled amount (may differ from amount on partial fills) |
| `senderAddress`   | `string` | Address that sent the crypto                                    |
| `transactionHash` | `string` | On-chain transaction hash                                       |
| `status`          | `string` | Status of the transaction                                       |

### Example: Full Event Handling

```javascript theme={null}
import { RampnowSdk, RampnowEventType } from '@rampnow/sdk'

const sdk = new RampnowSdk({
  apiKey: 'pk_live_YOUR_API_KEY',
  orderType: 'buy',
  dstCurrency: 'ETH',
  dstChain: 'ethereum',
})

sdk
  .on(RampnowEventType.WIDGET_READY, () => {
    console.log('Widget is ready')
  })
  .on(RampnowEventType.ORDER_CREATED, ({ payload }) => {
    console.log('Order created:', payload.orderUid)
  })
  .on(RampnowEventType.ORDER_COMPLETED, ({ payload }) => {
    console.log('Order completed:', payload.orderUid)
    console.log('Tx hash:', payload.transactionHash)
  })
  .on(RampnowEventType.ERROR, ({ payload }) => {
    console.error('Widget error:', payload.message)
  })
  .init()
```

***

## Commands

Commands are messages sent **from the SDK to the widget** using `sdk.send()`. This is the reverse direction of events.

<Warning>
  **Domain whitelisting required:** For security, the widget only accepts commands from whitelisted origins. To whitelist your domain, please [contact Rampnow](https://rampnow.io/contact-us). Commands sent from non-whitelisted origins will be silently ignored.
</Warning>

| Command                 | Payload               | Description                                          |
| ----------------------- | --------------------- | ---------------------------------------------------- |
| `UPDATE_PAYMENT_DETAIL` | `{ transactionHash }` | Update payment detail with a crypto transaction hash |

### Example: Submit a transaction hash from your wallet

```javascript theme={null}
import { RampnowSdk, RampnowEventType, RampnowCommandType } from '@rampnow/sdk'

const sdk = new RampnowSdk({ apiKey: 'pk_live_YOUR_API_KEY' })

// After your wallet completes a crypto transfer, send the hash to the widget
sdk.send(RampnowCommandType.UPDATE_PAYMENT_DETAIL, {
  transactionHash: '0xabc123...',
})

// Listen for confirmation that the payment is being processed
sdk.on(RampnowEventType.ORDER_PAYMENT_PROCESSING, ({ payload }) => {
  console.log('Payment updated:', payload.paymentStatus)
})
```

***

## When to Use the SDK

<AccordionGroup>
  <Accordion title="SDK vs Widget Mode (URL)" icon="code-compare">
    The SDK wraps the widget mode integration with a programmatic API. Use the SDK when you need:

    * Event-driven callbacks (order status updates)
    * Programmatic control (open/close the widget)
    * React integration via hooks
    * Type-safe configuration with TypeScript

    Use [Widget Mode](/api-reference/widget-mode) directly when you only need a simple iframe or redirect.
  </Accordion>

  <Accordion title="SDK vs Hosted Mode" icon="server">
    Use the SDK for a drop-in widget experience. Use [Hosted Mode](/api-reference/hosted-mode) when you need full control over the UI and want to build a custom flow using the REST APIs directly.
  </Accordion>
</AccordionGroup>

***

## Next Steps

* [View the live demo](https://demo.rampnow.io/)
* [Configure Webhooks](/api-reference/webhook) for server-side notifications
* [Explore Supported Assets](/quickstart/resources/supported-assets)
* [View API Documentation](/api-reference/overview)
