Docs/JavaScript SDK

JavaScript SDK

v1.0.0

Our official JavaScript/TypeScript SDK makes it easy to integrate Web3 Pay into your application with full type safety.

Installation

bash
# npm
-green-400">npm install @web3pay/sdk

# yarn
-green-400">yarn add @web3pay/sdk

# pnpm
-green-400">pnpm add @web3pay/sdk

Initialization

Create a client instance with your API key:

typescript
400">import { Web3Pay } 400">from 400">'@web3pay/sdk';

400">const client = 400">new Web3Pay({
  apiKey: 400">'wp3_live_sk_your_api_key',
  500">// Optional: custom base URL (for self-hosted deployments)
  baseUrl: 400">'https:500">//api.web3pay.io'
});

Create Onramp Session

Create a new session for fiat-to-crypto conversion:

typescript
400">const session = 400">await client.createSession({
  walletAddress: 400">'0x742d35Cc6634C0532925a3b844Bc9e7595f5fB',
  cryptoCurrency: 400">'ETH',
  fiatAmount: 10000,      500">// Amount in cents ($100.00)
  fiatCurrency: 400">'USD',
  metadata: {
    orderId: 400">'ord_12345',
    userId: 400">'usr_67890'
  }
});

console.log(session);
500">// {
500">//   session_id: 400">'onramp_sess_abc123',
500">//   client_secret: 400">'onramp_cs_secret_xyz',
500">//   publishable_key: 400">'pk_live_xxx',
500">//   expires_at: 400">'2024-01-15T12:30:00Z'
500">// }

Get Session Status

typescript
400">const status = 400">await client.getSession(400">'onramp_sess_abc123');

console.log(status);
500">// {
500">//   id: 400">'tx_xyz789',
500">//   session_id: 400">'onramp_sess_abc123',
500">//   status: 400">'completed',
500">//   wallet_address: 400">'0x742d35...',
500">//   crypto_currency: 400">'ETH',
500">//   crypto_amount: 400">'0.0412',
500">//   fiat_amount: 10000,
500">//   tx_hash: 400">'0x1234...',
500">//   created_at: 400">'2024-01-15T12:00:00Z',
500">//   completed_at: 400">'2024-01-15T12:08:00Z'
500">// }

List Transactions

typescript
400">const result = 400">await client.getTransactions({
  page: 1,
  limit: 20,
  status: 400">'completed'
});

console.log(result.transactions);  500">// Array of transaction objects
console.log(result.pagination);    500">// { page: 1, limit: 20, total: 156, pages: 8 }

500">// Get a single transaction
400">const tx = 400">await client.getTransaction(400">'tx_abc123');

Open Payment Widget

The SDK includes a built-in payment widget that handles the checkout flow:

typescript
500">// After creating a session, open the widget
client.openWidget(session.client_secret, {
  theme: 400">'light'  500">// or 400">'dark'
});

500">// Listen for events
client.on(400">'success', (data) => {
  console.log(400">'Payment successful!', data);
  500">// data contains transaction details
});

client.on(400">'error', (error) => {
  console.error(400">'Payment failed:', error);
});

client.on(400">'close', () => {
  console.log(400">'Widget closed by user');
});

500">// Programmatically close the widget
client.closeWidget();

Event Handling

Subscribe to widget events to handle user interactions:

EventDataDescription
successTransaction objectPayment completed successfully
errorError objectPayment failed
closeEmpty objectWidget closed by user
typescript
500">// Add event listener
400">const handleSuccess = (data: any) => {
  console.log(400">'Transaction completed:', data.tx_hash);
};
client.on(400">'success', handleSuccess);

500">// Remove event listener
client.off(400">'success', handleSuccess);

TypeScript Types

The SDK is fully typed. Here are the main interfaces:

typescript
400">interface Web3PayConfig {
  apiKey: string;
  baseUrl?: string;
}

400">interface CreateSessionParams {
  walletAddress: string;
  cryptoCurrency: string;
  fiatAmount: number;
  fiatCurrency: string;
  metadata?: Record<string, unknown>;
}

400">interface OnrampSession {
  session_id: string;
  client_secret: string;
  publishable_key: string;
  expires_at: string;
}

400">interface Transaction {
  id: string;
  session_id: string;
  wallet_address: string;
  crypto_currency: string;
  crypto_amount: string;
  fiat_currency: string;
  fiat_amount: number;
  platform_fee: number;
  status: 400">&#039;pending&#039; | 400">&#039;processing&#039; | 400">&#039;completed&#039; | 400">&#039;failed&#039;;
  created_at: string;
  completed_at: string | 400">null;
}

400">interface WidgetOptions {
  theme?: 400">&#039;light&#039; | 400">&#039;dark&#039;;
  containerId?: string;
}

Error Handling

The SDK throws errors that can be caught and handled:

typescript
400">try {
  400">const session = 400">await client.createSession({
    walletAddress: 400">&#039;invalid_address&#039;,
    cryptoCurrency: 400">&#039;ETH&#039;,
    fiatAmount: 10000,
    fiatCurrency: 400">&#039;USD&#039;
  });
} 400">catch (error) {
  400">if (error instanceof Error) {
    console.error(400">&#039;Error:&#039;, error.message);
    500">// 400">"The provided wallet address is not valid"
  }
}

Complete Example

Here's a complete example showing the typical integration flow:

typescript
1400">import { Web3Pay } 400">from 400">&#039;@web3pay/sdk&#039;;
2 
3500">// Initialize client
4400">const client = 400">new Web3Pay({
5 apiKey: process.env.WEB3PAY_API_KEY!
6});
7 
8400">async 400">function handleBuyCrypto(walletAddress: string, amount: number) {
9 400">try {
10 500">// 1. Create an onramp session
11 400">const session = 400">await client.createSession({
12 walletAddress,
13 cryptoCurrency: 400">&#039;ETH&#039;,
14 fiatAmount: amount * 100, 500">// Convert to cents
15 fiatCurrency: 400">&#039;USD&#039;,
16 metadata: {
17 userId: getCurrentUserId()
18 }
19 });
20 
21 500">// 2. Open the payment widget
22 client.openWidget(session.client_secret, {
23 theme: 400">&#039;dark&#039;
24 });
25 
26 500">// 3. Handle completion
27 client.on(400">&#039;success&#039;, 400">async (data) => {
28 console.log(400">&#039;Payment complete!&#039;);
29 console.log(400">&#039;TX Hash:&#039;, data.tx_hash);
30 
31 500">// Verify the transaction on your backend
32 400">const verified = 400">await verifyTransaction(session.session_id);
33 400">if (verified) {
34 showSuccessMessage(400">&#039;Crypto purchased successfully!&#039;);
35 }
36 });
37 
38 client.on(400">&#039;error&#039;, (error) => {
39 showErrorMessage(error.message);
40 });
41 
42 } 400">catch (error) {
43 console.error(400">&#039;Failed to create session:&#039;, error);
44 showErrorMessage(400">&#039;Unable to start purchase flow&#039;);
45 }
46}

Server-side Usage

The SDK can be used in Node.js environments for server-side operations:

typescript
500">// Express.js example
400">import express 400">from 400">&#039;express&#039;;
400">import { Web3Pay } 400">from 400">&#039;@web3pay/sdk&#039;;

400">const app = express();
400">const client = 400">new Web3Pay({
  apiKey: process.env.WEB3PAY_SECRET_KEY!
});

app.post(400">&#039;/api/create-onramp&#039;, 400">async (req, res) => {
  400">const { walletAddress, amount, currency } = req.body;

  400">try {
    400">const session = 400">await client.createSession({
      walletAddress,
      cryptoCurrency: currency,
      fiatAmount: amount,
      fiatCurrency: 400">&#039;USD&#039;,
      metadata: {
        userId: req.user.id
      }
    });

    res.json({
      clientSecret: session.client_secret,
      sessionId: session.session_id
    });
  } 400">catch (error) {
    res.status(400).json({ error: error.message });
  }
});
Back to home
Was this page helpful?