JavaScript SDK
The official JavaScript/TypeScript SDK for Pelago.
Installation
npm install @pelago/sdk
# or
yarn add @pelago/sdk
Quick Start
import { PelagoClient } from '@pelago/sdk';
const pelago = new PelagoClient({
apiKey: process.env.PELAGO_API_KEY,
apiSecret: process.env.PELAGO_API_SECRET,
environment: 'production' // or 'sandbox'
});
// Create a payment
const payment = await pelago.payments.create({
amount: 99.99,
currency: 'USD',
cryptocurrency: 'USDC',
network: 'stellar',
merchantWallet: 'GXXXXX...'
});
console.log('Payment URL:', payment.url);
Configuration
const pelago = new PelagoClient({
// Required
apiKey: 'pk_live_xxxxx',
apiSecret: 'sk_live_xxxxx',
// Optional
environment: 'production', // 'production' | 'sandbox'
timeout: 30000, // Request timeout in ms
maxRetries: 3, // Auto-retry failed requests
logger: console, // Custom logger
});
Payments
Create Payment
const payment = await pelago.payments.create({
amount: 100.00,
currency: 'USD',
cryptocurrency: 'USDC',
network: 'stellar',
merchantWallet: 'GXXXXX...',
redirectUrl: 'https://mystore.com/success',
webhookUrl: 'https://mystore.com/api/webhook',
expiresIn: 1800, // 30 minutes
metadata: {
orderId: 'ORD-12345',
customerEmail: 'customer@example.com'
}
});
Retrieve Payment
const payment = await pelago.payments.retrieve('pay_abc123');
console.log('Status:', payment.status);
List Payments
const payments = await pelago.payments.list({
status: 'completed',
limit: 20,
created_gte: '2025-01-01T00:00:00Z'
});
for (const payment of payments.data) {
console.log(`${payment.id}: ${payment.amount}`);
}
Cancel Payment
const payment = await pelago.payments.cancel('pay_abc123');
// Status will be 'cancelled'
Refunds
Create Refund
const refund = await pelago.refunds.create({
paymentId: 'pay_abc123',
amount: 50.00, // Partial refund
reason: 'Customer request'
});
List Refunds
const refunds = await pelago.refunds.list({
paymentId: 'pay_abc123'
});
Settlements
List Settlements
const settlements = await pelago.settlements.list({
status: 'completed',
startDate: '2025-01-01',
endDate: '2025-01-31'
});
Get Settlement Details
const settlement = await pelago.settlements.retrieve('stl_abc123');
console.log('Total:', settlement.totalAmount);
console.log('Payments:', settlement.paymentCount);
Webhooks
Verify Signature
import express from 'express';
const app = express();
app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => {
const signature = req.headers['x-pelago-signature'] as string;
const timestamp = req.headers['x-pelago-timestamp'] as string;
const isValid = pelago.webhooks.verify(
req.body,
signature,
timestamp,
process.env.WEBHOOK_SECRET
);
if (!isValid) {
return res.status(401).send('Invalid signature');
}
const event = JSON.parse(req.body.toString());
// Handle event...
res.status(200).json({ received: true });
});
Construct Event
const event = pelago.webhooks.constructEvent(
req.body,
req.headers['x-pelago-signature'],
req.headers['x-pelago-timestamp'],
process.env.WEBHOOK_SECRET
);
switch (event.type) {
case 'payment.completed':
console.log('Payment completed:', event.data.paymentId);
break;
}
Error Handling
import { PelagoError } from '@pelago/sdk';
try {
const payment = await pelago.payments.create(params);
} catch (error) {
if (error instanceof PelagoError) {
console.error('Type:', error.type);
console.error('Code:', error.code);
console.error('Message:', error.message);
console.error('Request ID:', error.requestId);
}
}
TypeScript Types
import type {
Payment,
PaymentCreateParams,
Refund,
Settlement,
WebhookEvent
} from '@pelago/sdk';
// Full type support
const params: PaymentCreateParams = {
amount: 100,
currency: 'USD',
cryptocurrency: 'USDC',
network: 'stellar',
merchantWallet: 'GXXXXX...'
};
const payment: Payment = await pelago.payments.create(params);
React Integration
import { useState } from 'react';
import { PelagoClient } from '@pelago/sdk';
// Initialize client (do this outside component)
const pelago = new PelagoClient({
apiKey: process.env.NEXT_PUBLIC_PELAGO_API_KEY,
environment: 'production'
});
function CheckoutButton({ amount, orderId }) {
const [loading, setLoading] = useState(false);
const handleCheckout = async () => {
setLoading(true);
try {
const payment = await pelago.payments.create({
amount,
currency: 'USD',
cryptocurrency: 'USDC',
network: 'stellar',
merchantWallet: process.env.NEXT_PUBLIC_WALLET,
metadata: { orderId }
});
window.location.href = payment.url;
} catch (error) {
console.error('Payment error:', error);
} finally {
setLoading(false);
}
};
return (
<button onClick={handleCheckout} disabled={loading}>
{loading ? 'Loading...' : `Pay $${amount}`}
</button>
);
}
Next.js API Route
// pages/api/create-payment.ts
import type { NextApiRequest, NextApiResponse } from 'next';
import { PelagoClient } from '@pelago/sdk';
const pelago = new PelagoClient({
apiKey: process.env.PELAGO_API_KEY!,
apiSecret: process.env.PELAGO_API_SECRET!,
environment: 'production'
});
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed' });
}
const { amount, orderId } = req.body;
try {
const payment = await pelago.payments.create({
amount,
currency: 'USD',
cryptocurrency: 'USDC',
network: 'stellar',
merchantWallet: process.env.MERCHANT_WALLET!,
webhookUrl: `${process.env.BASE_URL}/api/webhook`,
metadata: { orderId }
});
res.status(200).json({ paymentUrl: payment.url });
} catch (error) {
res.status(500).json({ error: error.message });
}
}