Sabong API v1.0

Get Transactions API

Overview

The Get Transactions API retrieves paginated transaction history for a user. This endpoint supports filtering by transaction type (credit/debit), date range, sorting, and pagination. Use this endpoint to display transaction history, reconcile accounts, or generate reports.

Endpoint

MethodEndpointAuthentication
GET/api/v1/get-transactionsSignature Required

Authentication

This endpoint requires Signature-based Authentication. You must include the following headers:

HeaderDescription
x-signatureHMAC-SHA256 signature of the request
x-timestampUnix timestamp (seconds) when the request was generated

Note: See Overview for detailed information on how signature authentication works and how to generate signatures.

Query Parameters

ParameterTypeRequiredDefaultDescription
clientIdstringYes-The unique client identifier
limitintegerNo10Number of results per page (min: 1, max: 100)
pageintegerNo1Page number (min: 1)
typestringNo-Filter by type: credit or debit
sortBystringNocreatedAtSort field: id, walletId, amount, currency, type, createdAt
sortOrderstringNodescSort order: asc or desc
dateFromstringNo-Start date (ISO 8601 format)
dateTostringNo-End date (ISO 8601 format)

Request Example

GET /api/v1/get-transactions?clientId=CLIENT_001&limit=20&page=1&type=credit&sortBy=createdAt&sortOrder=desc

Response

Success Response (200 OK)

{
  "status": "success",
  "message": "Transactions retrieved successfully",
  "data": {
    "clientId": "CLIENT_001",
    "totalCount": 150,
    "resultCount": 20,
    "totalPages": 8,
    "currentPage": 1,
    "limit": 20,
    "filters": {
      "type": "credit"
    },
    "sort": {
      "sortBy": "createdAt",
      "sortOrder": "desc"
    },
    "data": [
      {
        "id": 456,
        "walletId": 789,
        "amount": "100.50",
        "currency": "USD",
        "type": "credit",
        "referenceId": "BANK_TXN_123456",
        "description": "Deposit via bank transfer",
        "createdAt": "2026-02-01T14:30:00.000Z",
        "updatedAt": "2026-02-01T14:30:00.000Z"
      },
      {
        "id": 455,
        "walletId": 789,
        "amount": "250.00",
        "currency": "USD",
        "type": "credit",
        "referenceId": "BONUS_001",
        "description": "Welcome bonus",
        "createdAt": "2026-02-01T10:15:00.000Z",
        "updatedAt": "2026-02-01T10:15:00.000Z"
      }
    ]
  }
}

Response Fields

Pagination & Metadata

FieldTypeDescription
statusstringAlways "success" for successful requests
messagestringHuman-readable success message
data.clientIdstringClient identifier
data.totalCountintegerTotal number of transactions matching filters
data.resultCountintegerNumber of transactions in current response
data.totalPagesintegerTotal number of pages available
data.currentPageintegerCurrent page number
data.limitintegerNumber of results per page
data.filtersobjectApplied filters (type, date range, etc.)
data.sortobjectApplied sorting configuration

Transaction Object

FieldTypeDescription
idintegerUnique transaction ID
walletIdintegerAssociated wallet ID
amountstringTransaction amount (as string to preserve precision)
currencystringCurrency code (e.g., "USD")
typestringTransaction type: credit or debit
referenceIdstring | nullExternal reference ID if provided
descriptionstring | nullTransaction description
createdAtstringISO 8601 timestamp when transaction was created
updatedAtstringISO 8601 timestamp when transaction was last updated

Error Responses

Validation Error (400 Bad Request)

{
  "status": "failed",
  "message": "Validation failed",
  "data": {
    "errors": {
      "clientId": ["The clientId field is required."],
      "limit": ["The limit may not be greater than 100."],
      "type": ["The type must be one of: credit, debit."]
    }
  }
}

User Not Found (404 Not Found)

{
  "status": "failed",
  "message": "User not found",
  "data": null
}

Authentication Error (401 Unauthorized)

{
  "status": "error",
  "message": "Invalid signature",
  "data": null
}

Server Error (500 Internal Server Error)

{
  "status": "failed",
  "message": "Failed to retrieve transactions",
  "data": {
    "error": "Database connection failed"
  }
}

Usage Example

cURL

# Basic request
curl -X GET "https://wdcf.xerve.online/api/v1/get-transactions?clientId=CLIENT_001" \
  -H "x-signature: YOUR_SIGNATURE" \
  -H "x-timestamp: 1706802000"

# With filters
curl -X GET "https://wdcf.xerve.online/api/v1/get-transactions?clientId=CLIENT_001&limit=20&page=1&type=credit&sortBy=createdAt&sortOrder=desc" \
  -H "x-signature: YOUR_SIGNATURE" \
  -H "x-timestamp: 1706802000"

# With date range
curl -X GET "https://wdcf.xerve.online/api/v1/get-transactions?clientId=CLIENT_001&dateFrom=2026-01-01T00:00:00Z&dateTo=2026-01-31T23:59:59Z" \
  -H "x-signature: YOUR_SIGNATURE" \
  -H "x-timestamp: 1706802000"

Note: To generate the signature, refer to the Overview documentation.

JavaScript/TypeScript (with Axios)

import axios from 'axios';
// Import your signature generation function (see Overview)
import { generateSignature } from './signature-utils';

const API_BASE_URL = 'https://wdcf.xerve.online';
const CLIENT_SECRET = 'your-secret-key';

interface GetTransactionsQuery {
  clientId: string;
  limit?: number;
  page?: number;
  type?: 'credit' | 'debit';
  sortBy?: string;
  sortOrder?: 'asc' | 'desc';
  dateFrom?: string;
  dateTo?: string;
}

async function getTransactions(query: GetTransactionsQuery) {
  const timestamp = Math.floor(Date.now() / 1000);

  // Generate signature (see Overview for implementation)
  const signature = generateSignature({
    method: 'GET',
    path: '/api/v1/get-transactions',
    payload: query,
    secret: CLIENT_SECRET,
    timestamp
  });

  try {
    const response = await axios.get(
      `${API_BASE_URL}/api/v1/get-transactions`,
      {
        params: query,
        headers: {
          'x-signature': signature,
          'x-timestamp': timestamp.toString()
        }
      }
    );

    console.log('Total transactions:', response.data.data.totalCount);
    console.log('Transactions:', response.data.data.data);
    console.log('Current page:', response.data.data.currentPage);
    console.log('Total pages:', response.data.data.totalPages);
    return response.data;
  } catch (error: any) {
    console.error('Error:', error.response?.data || error.message);
    throw error;
  }
}

// Usage examples

// Get all transactions
getTransactions({ clientId: 'CLIENT_001' });

// Get credit transactions only
getTransactions({ 
  clientId: 'CLIENT_001', 
  type: 'credit',
  limit: 20,
  page: 1 
});

// Get transactions from last 30 days
const thirtyDaysAgo = new Date();
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);

getTransactions({
  clientId: 'CLIENT_001',
  dateFrom: thirtyDaysAgo.toISOString(),
  dateTo: new Date().toISOString(),
  sortBy: 'createdAt',
  sortOrder: 'desc'
});

Python

import requests
# Import your signature generation function (see Overview)
from signature_utils import generate_signature
import time
from datetime import datetime, timedelta

API_BASE_URL = 'https://wdcf.xerve.online'
CLIENT_SECRET = 'your-secret-key'

def get_transactions(
    client_id: str,
    limit: int = 10,
    page: int = 1,
    txn_type: str = None,
    sort_by: str = 'createdAt',
    sort_order: str = 'desc',
    date_from: str = None,
    date_to: str = None
):
    timestamp = int(time.time())
    payload = {
        "clientId": client_id,
        "limit": limit,
        "page": page,
        "sortBy": sort_by,
        "sortOrder": sort_order
    }
    
    if txn_type:
        payload["type"] = txn_type
    if date_from:
        payload["dateFrom"] = date_from
    if date_to:
        payload["dateTo"] = date_to

    # Generate signature (see Overview for implementation)
    signature = generate_signature(
        method="GET",
        path="/api/v1/get-transactions",
        payload=payload,
        secret=CLIENT_SECRET,
        timestamp=timestamp
    )

    headers = {
        "x-signature": signature,
        "x-timestamp": str(timestamp)
    }

    response = requests.get(
        f"{API_BASE_URL}/api/v1/get-transactions",
        params=payload,
        headers=headers
    )

    response.raise_for_status()
    data = response.json()
    print(f"Total transactions: {data['data']['totalCount']}")
    print(f"Current page: {data['data']['currentPage']} of {data['data']['totalPages']}")
    for txn in data['data']['data']:
        print(f"  {txn['type'].upper()}: {txn['amount']} - {txn.get('description', 'No description')}")
    return data

# Usage examples
if __name__ == "__main__":
    # Get all transactions
    get_transactions("CLIENT_001")
    
    # Get credit transactions only
    get_transactions("CLIENT_001", txn_type="credit", limit=20)
    
    # Get transactions from last 30 days
    date_from = (datetime.now() - timedelta(days=30)).isoformat()
    date_to = datetime.now().isoformat()
    get_transactions("CLIENT_001", date_from=date_from, date_to=date_to)

Pagination

The API uses offset-based pagination. Use the following approach to fetch all transactions:

async function getAllTransactions(clientId: string) {
  const allTransactions = [];
  let page = 1;
  let hasMore = true;
  
  while (hasMore) {
    const response = await getTransactions({
      clientId,
      limit: 100, // Max limit
      page
    });
    
    const { data, currentPage, totalPages } = response.data;
    allTransactions.push(...data);
    
    hasMore = currentPage < totalPages;
    page++;
  }
  
  return allTransactions;
}

Important Notes

  1. Default Sorting: By default, transactions are sorted by createdAt in descending order (newest first).
  2. Date Format: Use ISO 8601 format for date parameters (e.g., 2026-02-01T00:00:00Z).
  3. Maximum Limit: The maximum value for limit is 100. Requests with higher values will be rejected.
  4. Amount Precision: Amounts are returned as strings to preserve decimal precision. Convert to numbers carefully in your application.
  5. Transaction Types:
    • credit: Funds added to the wallet (deposits, bonuses, refunds)
    • debit: Funds removed from the wallet (withdrawals, bets, fees)
  6. Rate Limiting: Consider implementing caching for frequently accessed transaction history to reduce API load.

Common Use Cases

  • Transaction History: Display user's transaction history in a dashboard
  • Account Reconciliation: Reconcile internal records with transaction data
  • Reporting: Generate financial reports for specific date ranges
  • Audit Trail: Track all financial movements for compliance
  • Balance Verification: Cross-check balance changes against transaction history

Error Handling

Error CodePossible CausesResolution
400Invalid parameters (limit > 100, invalid type, etc.)Check validation errors in response
401Invalid signature or expired timestampVerify signature generation and ensure timestamp is current
404User not foundVerify clientId exists; may need to create user first
500Database or transaction service failureCheck server logs and retry

Calculating Balance from Transactions

You can calculate the current balance by summing all transactions:

function calculateBalance(transactions: any[]): number {
  return transactions.reduce((balance, txn) => {
    const amount = parseFloat(txn.amount);
    return txn.type === 'credit' ? balance + amount : balance - amount;
  }, 0);
}

Note: For production use, always rely on the Get Balance API for the current balance, as it reflects the database state directly.