JavaScript SDK
v1.0.0Our 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/sdkInitialization
Create a client instance with your API key:
typescript
400">import { Web3Pay } 400">from 400">039;@web3pay/sdk039;;
400">const client = 400">new Web3Pay({
apiKey: 400">039;wp3_live_sk_your_api_key039;,
500">// Optional: custom base URL (for self-hosted deployments)
baseUrl: 400">039;https:500">//api.web3pay.io039;
});Create Onramp Session
Create a new session for fiat-to-crypto conversion:
typescript
400">const session = 400">await client.createSession({
walletAddress: 400">039;0x742d35Cc6634C0532925a3b844Bc9e7595f5fB039;,
cryptoCurrency: 400">039;ETH039;,
fiatAmount: 10000, 500">// Amount in cents ($100.00)
fiatCurrency: 400">039;USD039;,
metadata: {
orderId: 400">039;ord_12345039;,
userId: 400">039;usr_67890039;
}
});
console.log(session);
500">// {
500">// session_id: 400">039;onramp_sess_abc123039;,
500">// client_secret: 400">039;onramp_cs_secret_xyz039;,
500">// publishable_key: 400">039;pk_live_xxx039;,
500">// expires_at: 400">039;2024-01-15T12:30:00Z039;
500">// }Get Session Status
typescript
400">const status = 400">await client.getSession(400">039;onramp_sess_abc123039;);
console.log(status);
500">// {
500">// id: 400">039;tx_xyz789039;,
500">// session_id: 400">039;onramp_sess_abc123039;,
500">// status: 400">039;completed039;,
500">// wallet_address: 400">039;0x742d35...039;,
500">// crypto_currency: 400">039;ETH039;,
500">// crypto_amount: 400">039;0.0412039;,
500">// fiat_amount: 10000,
500">// tx_hash: 400">039;0x1234...039;,
500">// created_at: 400">039;2024-01-15T12:00:00Z039;,
500">// completed_at: 400">039;2024-01-15T12:08:00Z039;
500">// }List Transactions
typescript
400">const result = 400">await client.getTransactions({
page: 1,
limit: 20,
status: 400">039;completed039;
});
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">039;tx_abc123039;);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">039;light039; 500">// or 400">039;dark039;
});
500">// Listen for events
client.on(400">039;success039;, (data) => {
console.log(400">039;Payment successful!039;, data);
500">// data contains transaction details
});
client.on(400">039;error039;, (error) => {
console.error(400">039;Payment failed:039;, error);
});
client.on(400">039;close039;, () => {
console.log(400">039;Widget closed by user039;);
});
500">// Programmatically close the widget
client.closeWidget();Event Handling
Subscribe to widget events to handle user interactions:
| Event | Data | Description |
|---|---|---|
| success | Transaction object | Payment completed successfully |
| error | Error object | Payment failed |
| close | Empty object | Widget closed by user |
typescript
500">// Add event listener
400">const handleSuccess = (data: any) => {
console.log(400">039;Transaction completed:039;, data.tx_hash);
};
client.on(400">039;success039;, handleSuccess);
500">// Remove event listener
client.off(400">039;success039;, 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;pending039; | 400">039;processing039; | 400">039;completed039; | 400">039;failed039;;
created_at: string;
completed_at: string | 400">null;
}
400">interface WidgetOptions {
theme?: 400">039;light039; | 400">039;dark039;;
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_address039;,
cryptoCurrency: 400">039;ETH039;,
fiatAmount: 10000,
fiatCurrency: 400">039;USD039;
});
} 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/sdk039;;2 3500">// Initialize client4400">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 session11 400">const session = 400">await client.createSession({12 walletAddress,13 cryptoCurrency: 400">039;ETH039;,14 fiatAmount: amount * 100, 500">// Convert to cents15 fiatCurrency: 400">039;USD039;,16 metadata: {17 userId: getCurrentUserId()18 }19 });20 21 500">// 2. Open the payment widget22 client.openWidget(session.client_secret, {23 theme: 400">039;dark039;24 });25 26 500">// 3. Handle completion27 client.on(400">039;success039;, 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 backend32 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;error039;, (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 flow039;);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;express039;;
400">import { Web3Pay } 400">from 400">039;@web3pay/sdk039;;
400">const app = express();
400">const client = 400">new Web3Pay({
apiKey: process.env.WEB3PAY_SECRET_KEY!
});
app.post(400">039;/api/create-onramp039;, 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;USD039;,
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 });
}
});