Code Examples
Ready-to-use code snippets for common integration scenarios. Copy, paste, and customize for your needs.
Create a Transaction
Create a new transaction with amount, currency, and customer details
Beginner💰 Transactions
const client = new TownClient({ apiKey: process.env.TOWN_API_KEY });
const transaction = await client.transactions.create({
amount: 100.00,
currency: 'USD',
customerId: 'cust_123456',
description: 'Deposit to wallet',
metadata: {
source: 'web',
campaignId: 'summer2025'
}
});
console.log('Transaction created:', transaction.id);
console.log('Status:', transaction.status);List Transactions with Pagination
Retrieve a paginated list of transactions with filters
Beginner💰 Transactions
const client = new TownClient({ apiKey: process.env.TOWN_API_KEY });
// Get first page
let transactions = await client.transactions.list({
limit: 100,
startingAfter: null,
status: 'completed'
});
console.log(`Found ${transactions.data.length} transactions`);
// Paginate through all results
while (transactions.hasMore) {
transactions = await client.transactions.list({
limit: 100,
startingAfter: transactions.data[transactions.data.length - 1].id
});
console.log(`Fetched ${transactions.data.length} more transactions`);
}Create and Update a Customer
Create a new customer and update their information
Beginner👤 Customers
const client = new TownClient({ apiKey: process.env.TOWN_API_KEY });
// Create a new customer
const customer = await client.customers.create({
email: 'john.doe@example.com',
name: 'John Doe',
phone: '+1234567890',
metadata: {
source: 'website_signup'
}
});
console.log('Customer created:', customer.id);
// Update customer information
const updatedCustomer = await client.customers.update(customer.id, {
name: 'John Smith',
phone: '+1987654321',
metadata: {
verified: true,
tier: 'premium'
}
});
console.log('Customer updated:', updatedCustomer.id);Verify Webhook Signatures
Securely verify that webhooks are sent from TOWN Platform
Intermediate🔗 Webhooks
const client = new TownClient({ apiKey: process.env.TOWN_API_KEY });
// Express.js webhook endpoint
app.post('/webhooks/town', express.raw({ type: 'application/json' }), (req, res) => {
const signature = req.headers['town-signature'];
const payload = req.body;
try {
// Verify the webhook signature
const event = client.webhooks.constructEvent(
payload,
signature,
process.env.WEBHOOK_SECRET
);
// Handle the event
switch (event.type) {
case 'transaction.completed':
console.log('Transaction completed:', event.data);
// Process successful transaction
break;
case 'transaction.failed':
console.log('Transaction failed:', event.data);
// Handle failed transaction
break;
default:
console.log('Unhandled event type:', event.type);
}
res.json({ received: true });
} catch (err) {
console.error('Webhook signature verification failed:', err.message);
return res.status(400).send(`Webhook Error: ${err.message}`);
}
});Generate Analytics Report
Fetch analytics data and generate a report with aggregations
Intermediate📊 Reports & Analytics
const client = new TownClient({ apiKey: process.env.TOWN_API_KEY });
// Get analytics for the last 30 days
const endDate = new Date();
const startDate = new Date();
startDate.setDate(startDate.getDate() - 30);
const analytics = await client.reports.analytics({
startDate: startDate.toISOString(),
endDate: endDate.toISOString(),
metrics: ['revenue', 'transactions', 'customers'],
groupBy: 'day'
});
// Calculate totals
const totalRevenue = analytics.data.reduce((sum, day) => sum + day.revenue, 0);
const totalTransactions = analytics.data.reduce((sum, day) => sum + day.transactions, 0);
const avgTransactionValue = totalRevenue / totalTransactions;
console.log(`Total Revenue: $${totalRevenue.toFixed(2)}`);
console.log(`Total Transactions: ${totalTransactions}`);
console.log(`Average Transaction: $${avgTransactionValue.toFixed(2)}`);
// Export to CSV
const csv = analytics.data.map(day =>
`${day.date},${day.revenue},${day.transactions},${day.customers}`
).join('\n');
console.log('CSV Export:\n', csv);Comprehensive Error Handling
Handle different types of API errors gracefully
Intermediate🔐 Security
const client = new TownClient({ apiKey: process.env.TOWN_API_KEY });
async function createTransactionWithErrorHandling() {
try {
const transaction = await client.transactions.create({
amount: 100.00,
currency: 'USD',
customerId: 'cust_123456'
});
return { success: true, data: transaction };
} catch (error) {
// Handle different error types
if (error.type === 'authentication_error') {
console.error('Invalid API key');
return { success: false, error: 'Authentication failed' };
} else if (error.type === 'rate_limit_error') {
console.error('Rate limit exceeded');
// Wait and retry
await new Promise(resolve => setTimeout(resolve, 1000));
return createTransactionWithErrorHandling();
} else if (error.type === 'validation_error') {
console.error('Validation failed:', error.message);
return { success: false, error: error.message };
} else if (error.type === 'api_error') {
console.error('API error:', error.message);
return { success: false, error: 'Server error' };
} else {
console.error('Unknown error:', error);
return { success: false, error: 'An unexpected error occurred' };
}
}
}
const result = await createTransactionWithErrorHandling();
if (result.success) {
console.log('Transaction created:', result.data.id);
} else {
console.error('Failed to create transaction:', result.error);
}Idempotent Requests
Safely retry failed requests without duplicating operations
Advanced🔐 Security
const { v4: uuidv4 } = require('uuid');
const client = new TownClient({ apiKey: process.env.TOWN_API_KEY });
async function createIdempotentTransaction(params) {
// Generate a unique idempotency key
const idempotencyKey = uuidv4();
const maxRetries = 3;
let attempt = 0;
while (attempt < maxRetries) {
try {
const transaction = await client.transactions.create(params, {
idempotencyKey: idempotencyKey
});
console.log('Transaction created:', transaction.id);
return transaction;
} catch (error) {
attempt++;
if (error.type === 'network_error' && attempt < maxRetries) {
console.log(`Retry attempt ${attempt} of ${maxRetries}`);
// Exponential backoff
await new Promise(resolve =>
setTimeout(resolve, Math.pow(2, attempt) * 1000)
);
continue;
}
throw error;
}
}
}
// Usage
const transaction = await createIdempotentTransaction({
amount: 100.00,
currency: 'USD',
customerId: 'cust_123456'
});