Skip to main content

Analytics API

The Analytics API provides comprehensive business insights, performance metrics, and reporting data to help you understand your checkout performance and optimize your business.

Quick Start

Basic Analytics Request

const response = await fetch('https://api.torque.fi/v1/analytics/overview', {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});

const analytics = await response.json();
console.log('Total Revenue:', analytics.totalRevenue);
console.log('Order Count:', analytics.orderCount);

Available Metrics

Business Overview

  • Revenue: Total revenue, monthly trends, growth rates
  • Orders: Order count, conversion rates, average order value
  • Customers: Customer count, repeat purchase rate, lifetime value
  • Performance: Checkout completion rates, payment success rates

Detailed Analytics

  • Product Performance: Best-selling products, inventory insights
  • Customer Behavior: Geographic distribution, device usage, payment preferences
  • Operational Metrics: Webhook delivery rates, API usage, error rates

📋 Endpoints

Business Overview

GET /v1/analytics/overview

Get a comprehensive overview of your business performance.

Query Parameters

  • period (string): Time period (day, week, month, quarter, year)
  • startDate (string): Start date (ISO 8601)
  • endDate (string): End date (ISO 8601)
  • currency (string): Currency for monetary values (default: USD)

Response

Success (200)

{
"success": true,
"period": {
"start": "2024-01-01T00:00:00Z",
"end": "2024-01-31T23:59:59Z",
"type": "month"
},
"revenue": {
"total": 15420.50,
"currency": "USD",
"previousPeriod": 12850.75,
"growth": 20.0,
"trend": "up"
},
"orders": {
"total": 342,
"completed": 298,
"cancelled": 44,
"conversionRate": 87.1,
"averageValue": 45.09
},
"customers": {
"total": 298,
"new": 156,
"returning": 142,
"repeatRate": 47.7
},
"performance": {
"checkoutCompletion": 89.2,
"paymentSuccess": 94.8,
"averageCheckoutTime": 180
}
}

Revenue Analytics

GET /v1/analytics/revenue

Detailed revenue breakdown and trends.

Query Parameters

  • period (string): Time period (day, week, month, quarter, year)
  • startDate (string): Start date (ISO 8601)
  • endDate (string): End date (ISO 8601)
  • groupBy (string): Group by (day, week, month)
  • currency (string): Currency (default: USD)

Response

Success (200)

{
"success": true,
"period": {
"start": "2024-01-01T00:00:00Z",
"end": "2024-01-31T23:59:59Z"
},
"summary": {
"total": 15420.50,
"currency": "USD",
"previousPeriod": 12850.75,
"growth": 20.0
},
"breakdown": [
{
"date": "2024-01-01",
"revenue": 450.25,
"orders": 12,
"averageOrder": 37.52
},
{
"date": "2024-01-02",
"revenue": 520.75,
"orders": 15,
"averageOrder": 34.72
}
],
"trends": {
"dailyGrowth": 2.1,
"weeklyGrowth": 15.3,
"monthlyGrowth": 20.0
}
}

Order Analytics

GET /v1/analytics/orders

Comprehensive order performance metrics.

Query Parameters

  • period (string): Time period
  • startDate (string): Start date
  • endDate (string): End date
  • status (string): Filter by order status
  • groupBy (string): Group by (day, week, month, product, customer)

Response

Success (200)

{
"success": true,
"summary": {
"total": 342,
"completed": 298,
"cancelled": 44,
"pending": 0,
"conversionRate": 87.1
},
"breakdown": {
"byStatus": [
{
"status": "completed",
"count": 298,
"percentage": 87.1,
"revenue": 13420.50
},
{
"status": "cancelled",
"count": 44,
"percentage": 12.9,
"revenue": 0
}
],
"byProduct": [
{
"productId": "prod_1",
"name": "Product A",
"orders": 156,
"revenue": 4680.00,
"averageOrder": 30.00
}
]
},
"trends": {
"dailyOrders": [12, 15, 18, 20, 22, 25, 28],
"conversionTrend": [85.2, 86.1, 87.3, 88.0, 87.8, 87.1, 87.1]
}
}

Customer Analytics

GET /v1/analytics/customers

Customer behavior and demographics insights.

Query Parameters

  • period (string): Time period
  • startDate (string): Start date
  • endDate (string): End date
  • groupBy (string): Group by (day, week, month, country, device)

Response

Success (200)

{
"success": true,
"summary": {
"total": 298,
"new": 156,
"returning": 142,
"repeatRate": 47.7,
"lifetimeValue": 51.75
},
"demographics": {
"byCountry": [
{
"country": "US",
"customers": 245,
"percentage": 82.2,
"revenue": 12675.50
},
{
"country": "CA",
"customers": 53,
"percentage": 17.8,
"revenue": 2745.00
}
],
"byDevice": [
{
"device": "desktop",
"customers": 178,
"percentage": 59.7,
"revenue": 9205.50
},
{
"device": "mobile",
"customers": 120,
"percentage": 40.3,
"revenue": 6215.00
}
]
},
"behavior": {
"averageOrderValue": 45.09,
"repeatPurchaseRate": 47.7,
"daysToRepeat": 45.2
}
}

Product Performance

GET /v1/analytics/products

Product-specific performance metrics.

Query Parameters

  • period (string): Time period
  • startDate (string): Start date
  • endDate (string): End date
  • productId (string): Specific product ID
  • limit (number): Number of products to return

Response

Success (200)

{
"success": true,
"summary": {
"totalProducts": 45,
"activeProducts": 42,
"totalRevenue": 15420.50
},
"products": [
{
"productId": "prod_1",
"name": "Product A",
"orders": 156,
"revenue": 4680.00,
"averageOrder": 30.00,
"conversionRate": 92.3,
"trend": "up"
},
{
"productId": "prod_2",
"name": "Product B",
"orders": 89,
"revenue": 3560.00,
"averageOrder": 40.00,
"conversionRate": 88.1,
"trend": "stable"
}
],
"insights": {
"bestSeller": "prod_1",
"highestRevenue": "prod_1",
"bestConversion": "prod_1"
}
}

Performance Metrics

GET /v1/analytics/performance

System and operational performance metrics.

Query Parameters

  • period (string): Time period
  • startDate (string): Start date
  • endDate (string): End date
  • metric (string): Specific metric (checkout, payment, webhook)

Response

Success (200)

{
"success": true,
"checkout": {
"completionRate": 89.2,
"averageTime": 180,
"abandonmentRate": 10.8,
"trend": "up"
},
"payment": {
"successRate": 94.8,
"failureRate": 5.2,
"averageProcessingTime": 2.5,
"trend": "stable"
},
"webhooks": {
"deliveryRate": 99.1,
"failureRate": 0.9,
"averageResponseTime": 150,
"trend": "up"
},
"api": {
"uptime": 99.9,
"averageResponseTime": 45,
"errorRate": 0.1,
"trend": "stable"
}
}

Data Export

Export Analytics

POST /v1/analytics/export

Export analytics data in various formats.

Request Body

{
"type": "revenue",
"format": "csv",
"period": {
"start": "2024-01-01T00:00:00Z",
"end": "2024-01-31T23:59:59Z"
},
"filters": {
"status": "completed",
"currency": "USD"
}
}

Response

Success (200)

{
"success": true,
"exportId": "export_abc123",
"status": "processing",
"estimatedCompletion": "2024-01-15T10:30:00Z",
"downloadUrl": "https://api.torque.fi/v1/analytics/export/export_abc123/download"
}

Get Export Status

GET /v1/analytics/export/{exportId}

Check the status of an export job.

Response

Success (200)

{
"success": true,
"exportId": "export_abc123",
"status": "completed",
"createdAt": "2024-01-15T10:00:00Z",
"completedAt": "2024-01-15T10:25:00Z",
"downloadUrl": "https://api.torque.fi/v1/analytics/export/export_abc123/download",
"expiresAt": "2024-01-22T10:25:00Z"
}

Advanced Filtering

Filter Options

// Complex analytics query with filters
const response = await fetch('https://api.torque.fi/v1/analytics/orders', {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
period: 'month',
startDate: '2024-01-01T00:00:00Z',
endDate: '2024-01-31T23:59:59Z',
filters: {
status: ['completed', 'processing'],
minAmount: 25.00,
maxAmount: 100.00,
countries: ['US', 'CA'],
devices: ['desktop', 'mobile']
},
groupBy: 'day',
sortBy: 'revenue',
sortOrder: 'desc'
})
});

Filter Types

  • Status: Filter by order status
  • Amount: Filter by order value ranges
  • Geography: Filter by country, region, city
  • Device: Filter by device type
  • Time: Filter by specific time periods
  • Customer: Filter by customer segments

📱 Complete Examples

JavaScript Analytics Client

class TorqueAnalytics {
constructor(apiKey) {
this.apiKey = apiKey;

}

async getOverview(period = 'month', startDate = null, endDate = null) {
const params = new URLSearchParams({ period });
if (startDate) params.append('startDate', startDate);
if (endDate) params.append('endDate', endDate);

const response = await fetch(`https://api.torque.fi/v1/analytics/overview?${params}`, {
headers: {
'Authorization': `Bearer ${this.apiKey}`
}
});

if (!response.ok) {
throw new Error('Failed to fetch analytics overview');
}

return response.json();
}

async getRevenue(period = 'month', groupBy = 'day') {
const params = new URLSearchParams({ period, groupBy });

const response = await fetch(`https://api.torque.fi/v1/analytics/revenue?${params}`, {
headers: {
'Authorization': `Bearer ${this.apiKey}`
}
});

if (!response.ok) {
throw new Error('Failed to fetch revenue analytics');
}

return response.json();
}

async getOrders(filters = {}) {
const params = new URLSearchParams();
Object.entries(filters).forEach(([key, value]) => {
if (Array.isArray(value)) {
value.forEach(v => params.append(key, v));
} else {
params.append(key, value);
}
});

const response = await fetch(`https://api.torque.fi/v1/analytics/orders?${params}`, {
headers: {
'Authorization': `Bearer ${this.apiKey}`
}
});

if (!response.ok) {
throw new Error('Failed to fetch order analytics');
}

return response.json();
}

async exportData(type, format, period, filters = {}) {
const response = await fetch(`https://api.torque.fi/v1/analytics/export`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
type,
format,
period,
filters
})
});

if (!response.ok) {
throw new Error('Failed to create export');
}

return response.json();
}

async getExportStatus(exportId) {
const response = await fetch(`https://api.torque.fi/v1/analytics/export/${exportId}`, {
headers: {
'Authorization': `Bearer ${this.apiKey}`
}
});

if (!response.ok) {
throw new Error('Failed to get export status');
}

return response.json();
}
}

// Usage
const analytics = new TorqueAnalytics(apiKey);

// Get business overview
const overview = await analytics.getOverview('month');
console.log('Monthly Revenue:', overview.revenue.total);

// Get revenue breakdown
const revenue = await analytics.getRevenue('month', 'day');
console.log('Daily Revenue:', revenue.breakdown);

// Get order analytics with filters
const orders = await analytics.getOrders({
status: ['completed'],
minAmount: 25.00,
countries: ['US']
});
console.log('Filtered Orders:', orders.summary);

// Export data
const exportJob = await analytics.exportData('revenue', 'csv', {
start: '2024-01-01T00:00:00Z',
end: '2024-01-31T23:59:59Z'
});

// Check export status
const exportStatus = await analytics.getExportStatus(exportJob.exportId);
if (exportStatus.status === 'completed') {
console.log('Download URL:', exportStatus.downloadUrl);
}

Dashboard Integration

// Real-time dashboard updates
class AnalyticsDashboard {
constructor(analytics) {
this.analytics = analytics;
this.updateInterval = 300000; // 5 minutes
this.charts = {};
}

async initialize() {
await this.loadInitialData();
this.startAutoUpdate();
}

async loadInitialData() {
try {
const [overview, revenue, orders] = await Promise.all([
this.analytics.getOverview('month'),
this.analytics.getRevenue('month', 'day'),
this.analytics.getOrders({ status: ['completed'] })
]);

this.updateDashboard(overview, revenue, orders);
} catch (error) {
console.error('Failed to load analytics:', error);
}
}

updateDashboard(overview, revenue, orders) {
// Update revenue chart
this.updateRevenueChart(revenue.breakdown);

// Update order metrics
this.updateOrderMetrics(orders.summary);

// Update performance indicators
this.updatePerformanceIndicators(overview.performance);
}

updateRevenueChart(data) {
const chart = this.charts.revenue;
if (chart) {
chart.data.labels = data.map(d => d.date);
chart.data.datasets[0].data = data.map(d => d.revenue);
chart.update();
}
}

updateOrderMetrics(data) {
document.getElementById('total-orders').textContent = data.total;
document.getElementById('conversion-rate').textContent = `${data.conversionRate}%`;
document.getElementById('average-order').textContent = `$${data.averageValue.toFixed(2)}`;
}

updatePerformanceIndicators(data) {
document.getElementById('checkout-completion').textContent = `${data.checkoutCompletion}%`;
document.getElementById('payment-success').textContent = `${data.paymentSuccess}%`;
}

startAutoUpdate() {
setInterval(async () => {
await this.loadInitialData();
}, this.updateInterval);
}
}

// Initialize dashboard
const dashboard = new AnalyticsDashboard(analytics);
dashboard.initialize();

Visualization Examples

Chart.js Integration

// Revenue trend chart
const revenueCtx = document.getElementById('revenue-chart').getContext('2d');
const revenueChart = new Chart(revenueCtx, {
type: 'line',
data: {
labels: [],
datasets: [{
label: 'Daily Revenue',
data: [],
borderColor: '#3B82F6',
backgroundColor: 'rgba(59, 130, 246, 0.1)',
tension: 0.4
}]
},
options: {
responsive: true,
plugins: {
legend: {
position: 'top',
},
title: {
display: true,
text: 'Revenue Trend'
}
},
scales: {
y: {
beginAtZero: true,
ticks: {
callback: function(value) {
return '$' + value.toLocaleString();
}
}
}
}
}
});

// Store chart reference
this.charts.revenue = revenueChart;

Next Steps


Ready to track your performance? Set up analytics in your business dashboard or contact our team for custom reporting solutions.