JavaScript SDK
The official CyberPay JavaScript/TypeScript SDK provides a convenient way to integrate cross-chain payments into your web applications.
Installation
npm install @cyberpay/sdk
# or
yarn add @cyberpay/sdk
# or
pnpm add @cyberpay/sdkQuick Start
import { CyberPaySDK } from '@cyberpay/sdk';
const sdk = new CyberPaySDK({
apiKey: 'YOUR_API_KEY',
environment: 'production' // or 'testnet'
});
// Create a checkout session
const checkout = await sdk.checkout.create({
merchantId: 'your_merchant_id',
amount: '99.99',
currency: 'USDC',
productInfo: {
name: 'Premium Subscription'
},
returnUrl: 'https://yourstore.com/success'
});
console.log('Checkout created:', checkout.checkoutId);Configuration
SDK Options
interface CyberPaySDKOptions {
apiKey: string; // Your API key
environment?: 'production' | 'testnet'; // Default: 'production'
timeout?: number; // Request timeout in ms (default: 30000)
retries?: number; // Number of retries (default: 3)
baseUrl?: string; // Custom API base URL
}Environment Setup
// Production
const sdk = new CyberPaySDK({
apiKey: process.env.CYBERPAY_API_KEY,
environment: 'production'
});
// Testnet
const sdk = new CyberPaySDK({
apiKey: process.env.CYBERPAY_TESTNET_API_KEY,
environment: 'testnet'
});API Methods
Checkout Methods
// Create checkout session
const checkout = await sdk.checkout.create({
merchantId: 'merchant_123',
amount: '100.00',
currency: 'USDC',
productInfo: { name: 'Product' },
returnUrl: 'https://example.com/success'
});
// Get checkout details
const checkoutDetails = await sdk.checkout.get('checkout_123');Quote Methods
// Get payment quote
const quote = await sdk.quote.get({
checkoutId: 'checkout_123',
paymentToken: {
address: '0x...',
decimals: 6,
symbol: 'USDC',
chainId: 137
},
settlementToken: {
address: '0x...',
decimals: 6,
symbol: 'USDC',
chainId: 1
},
amount: '100.00'
});
// Refresh quote
const refreshedQuote = await sdk.quote.refresh('quote_123');Order Methods
// Create order
const order = await sdk.order.create({
checkoutId: 'checkout_123',
quoteId: 'quote_123',
userAddress: '0x...'
});
// Get order status
const status = await sdk.order.getStatus('order_123');Payment Methods
// Execute payment
const execution = await sdk.payment.execute({
orderId: 'order_123',
userAddress: '0x...'
});
// Get payment status
const paymentStatus = await sdk.payment.getStatus('order_123');Token Methods
// Get token prices
const prices = await sdk.tokens.getPrices({
tokens: ['ETH', 'USDC', 'MATIC']
});
// Get supported tokens
const supportedTokens = await sdk.tokens.getSupported();
// Get single token price
const ethPrice = await sdk.tokens.getPrice('ETH');Chain Methods
// Get supported chains
const chains = await sdk.chains.getSupported();
// Get chain by ID
const ethereum = await sdk.chains.getById(1);Error Handling
import { CyberPayError, CyberPayAPIError } from '@cyberpay/sdk';
try {
const quote = await sdk.quote.get({...});
} catch (error) {
if (error instanceof CyberPayAPIError) {
console.error('API Error:', error.code, error.message);
console.error('Details:', error.details);
} else if (error instanceof CyberPayError) {
console.error('SDK Error:', error.message);
} else {
console.error('Unknown error:', error);
}
}Error Types
// API errors from the server
class CyberPayAPIError extends Error {
code: string;
details?: any;
statusCode: number;
}
// SDK-level errors
class CyberPayError extends Error {
cause?: Error;
}
// Network/timeout errors
class CyberPayNetworkError extends CyberPayError {
timeout: boolean;
}TypeScript Support
The SDK is written in TypeScript and provides full type definitions:
import {
CheckoutCreateRequest,
CheckoutResponse,
QuoteRequest,
QuoteResponse,
OrderCreateRequest,
OrderResponse,
PaymentExecuteRequest,
PaymentExecuteResponse
} from '@cyberpay/sdk';
// All request/response types are available
const checkoutRequest: CheckoutCreateRequest = {
merchantId: 'merchant_123',
amount: '100.00',
currency: 'USDC',
productInfo: {
name: 'Premium Subscription'
},
returnUrl: 'https://example.com/success'
};Webhook Utilities
import { CyberPaySDK } from '@cyberpay/sdk';
const sdk = new CyberPaySDK({ apiKey: 'your_key' });
// Verify webhook signature
const isValid = sdk.webhooks.verify(
payload, // Raw request body
signature, // X-CyberPay-Signature header
webhookSecret // Your webhook secret
);
if (isValid) {
// Process webhook
console.log('Webhook verified:', payload);
}React Integration
import { useState, useEffect } from 'react';
import { CyberPaySDK } from '@cyberpay/sdk';
function PaymentComponent() {
const [sdk] = useState(() => new CyberPaySDK({
apiKey: process.env.REACT_APP_CYBERPAY_API_KEY
}));
const [checkout, setCheckout] = useState(null);
const [loading, setLoading] = useState(false);
const createCheckout = async () => {
setLoading(true);
try {
const result = await sdk.checkout.create({
merchantId: 'merchant_123',
amount: '99.99',
currency: 'USDC',
productInfo: { name: 'Premium Plan' },
returnUrl: window.location.origin + '/success'
});
setCheckout(result);
} catch (error) {
console.error('Error:', error);
} finally {
setLoading(false);
}
};
return (
<div>
<button onClick={createCheckout} disabled={loading}>
{loading ? 'Creating...' : 'Pay with Crypto'}
</button>
{checkout && (
<div>
<p>Checkout ID: {checkout.checkoutId}</p>
<a href={checkout.paymentUrl}>Complete Payment</a>
</div>
)}
</div>
);
}Node.js Server Example
import express from 'express';
import { CyberPaySDK } from '@cyberpay/sdk';
const app = express();
const sdk = new CyberPaySDK({
apiKey: process.env.CYBERPAY_API_KEY
});
app.use(express.json());
// Create checkout endpoint
app.post('/api/checkout', async (req, res) => {
try {
const checkout = await sdk.checkout.create({
merchantId: process.env.CYBERPAY_MERCHANT_ID,
amount: req.body.amount,
currency: req.body.currency,
productInfo: req.body.productInfo,
returnUrl: req.body.returnUrl,
metadata: {
userId: req.body.userId,
orderId: req.body.orderId
}
});
res.json(checkout);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Webhook handler
app.post('/api/webhooks/cyberpay', (req, res) => {
const signature = req.headers['x-cyberpay-signature'];
const payload = req.body;
if (!sdk.webhooks.verify(payload, signature, process.env.WEBHOOK_SECRET)) {
return res.status(401).send('Invalid signature');
}
// Process webhook
console.log('Webhook received:', payload);
res.status(200).send('OK');
});
app.listen(3000);Best Practices
API Key Security
- Never expose API keys in client-side code
- Use environment variables for API keys
- Rotate API keys regularly
- Use different keys for different environments
Error Handling
- Always wrap SDK calls in try-catch blocks
- Implement retry logic for network errors
- Log errors for debugging
- Provide meaningful error messages to users
Performance
- Cache SDK instances (don't create new ones for each request)
- Use appropriate timeout values
- Implement request deduplication for identical calls
- Monitor API usage and optimize accordingly
Migration Guide
From v1.x to v2.x
// v1.x (deprecated)
const sdk = new CyberPay('api_key');
const quote = await sdk.getQuote({...});
// v2.x (current)
const sdk = new CyberPaySDK({ apiKey: 'api_key' });
const quote = await sdk.quote.get({...});Support
- 📧 Email: support@cyberpay.org
- 💬 Telegram: @cyberpay_support
- 📖 GitHub: cyberpay/cyberpay-js
