> ## Documentation Index
> Fetch the complete documentation index at: https://docs.monei.cc/llms.txt
> Use this file to discover all available pages before exploring further.

# History

> View and manage your bill payment history

## Overview

Track all your bill payments, view receipts, and analyze spending patterns. This guide covers accessing payment history and generating reports.

**What you'll learn:**

* Get payment history
* Filter by category
* Search payments
* View payment details
* Export records

***

## Get Payment History

Retrieve all your bill payments.

<CodeGroup>
  ```javascript Node.js theme={null}
  import MoneiSDK from 'monei-sdk';

  const monei = new MoneiSDK({
    apiKey: process.env.MONEI_API_KEY,
  });

  // Get all bill payments
  const payments = await monei.billsRecord.getBills({
    page: 1,
    limit: 20
  });

  console.log(`Total Payments: ${payments.pagination.total}\n`);

  payments.data.forEach(payment => {
    console.log(`${payment.billerName} - ₦${payment.amount}`);
    console.log(`  Customer: ${payment.customerName}`);
    console.log(`  Status: ${payment.status}`);
    console.log(`  Date: ${new Date(payment.createdAt).toLocaleString()}`);
    console.log(`  Reference: ${payment.reference}`);
    console.log('');
  });
  ```

  ```python Python theme={null}
  from monei import MoneiClient

  monei = MoneiClient(
      api_key=os.getenv('MONEI_API_KEY')
  )

  # Get payment history
  payments = monei.bills_record.get_bills(
      page=1,
      limit=20
  )

  print(f'Total Payments: {payments.pagination.total}\n')

  for payment in payments.data:
      print(f'{payment.biller_name} - ₦{payment.amount}')
      print(f'  Customer: {payment.customer_name}')
      print(f'  Status: {payment.status}')
      print(f'  Date: {payment.created_at}')
      print(f'  Reference: {payment.reference}')
      print()
  ```

  ```bash cURL theme={null}
  curl "https://api.monei.cc/api/v1/bills/history?page=1&limit=20" \
    -H "x-api-key: YOUR_API_KEY"
  ```
</CodeGroup>

**Query Parameters:**

| Parameter   | Type   | Description                                         |
| ----------- | ------ | --------------------------------------------------- |
| `page`      | number | Page number (default: 1)                            |
| `limit`     | number | Items per page (default: 10, max: 100)              |
| `status`    | string | Filter by status (successful, failed, pending)      |
| `category`  | string | Filter by category (airtime, data, cable\_tv, etc.) |
| `startDate` | string | Start date (YYYY-MM-DD)                             |
| `endDate`   | string | End date (YYYY-MM-DD)                               |
| `billerId`  | string | Filter by biller                                    |

**Response:**

```json theme={null}
{
  "statusCode": 200,
  "message": "Payment history retrieved successfully",
  "data": [
    {
      "reference": "BILL-ABC123XYZ",
      "status": "successful",
      "amount": 1000,
      "fee": 0,
      "totalAmount": 1000,
      "billerName": "MTN Nigeria",
      "billerId": "mtn-ng",
      "category": "airtime",
      "customerName": "JOHN DOE",
      "customerId": "08012345678",
      "type": "PREPAID",
      "createdAt": "2024-02-15T10:30:00Z"
    }
  ],
  "pagination": {
    "page": 1,
    "limit": 20,
    "total": 150,
    "pages": 8
  }
}
```

***

## Filter by Category

Get payments for specific bill category.

<CodeGroup>
  ```javascript Node.js theme={null}
  // Get airtime payments
  const airtimePayments = await monei.billsRecord.getBills({
    category: 'airtime',
    limit: 10
  });

  console.log('Airtime Payments:\n');
  airtimePayments.data.forEach(p => {
    console.log(`${p.billerName}: ₦${p.amount} to ${p.customerId}`);
    console.log(`  Date: ${new Date(p.createdAt).toLocaleDateString()}`);
  });

  // Get electricity payments
  const electricityPayments = await monei.billsRecord.getBills({
    category: 'electricity',
    limit: 10
  });

  console.log('\nElectricity Payments:\n');
  electricityPayments.data.forEach(p => {
    console.log(`${p.billerName}: ₦${p.amount}`);
    console.log(`  Meter: ${p.customerId}`);
    console.log(`  Token: ${p.token || 'N/A'}`);
  });

  // Get cable TV payments
  const cablePayments = await monei.billsRecord.getBills({
    category: 'cable_tv',
    limit: 10
  });

  console.log('\nCable TV Payments:\n');
  cablePayments.data.forEach(p => {
    console.log(`${p.billerName}: ₦${p.amount}`);
    console.log(`  Smartcard: ${p.customerId}`);
    console.log(`  Package: ${p.packageName || 'N/A'}`);
  });
  ```

  ```python Python theme={null}
  # Airtime payments
  airtime_payments = monei.bills_record.get_bills(
      category='airtime',
      limit=10
  )

  print('Airtime Payments:\n')
  for p in airtime_payments.data:
      print(f'{p.biller_name}: ₦{p.amount} to {p.customer_id}')
      print(f'  Date: {p.created_at}')

  # Electricity payments
  electricity_payments = monei.bills_record.get_bills(
      category='electricity',
      limit=10
  )

  print('\nElectricity Payments:\n')
  for p in electricity_payments.data:
      print(f'{p.biller_name}: ₦{p.amount}')
      print(f'  Meter: {p.customer_id}')
      print(f'  Token: {p.token or "N/A"}')
  ```
</CodeGroup>

***

## Filter by Date Range

Get payments within a specific period.

<CodeGroup>
  ```javascript Node.js theme={null}
  // Get this month's payments
  const thisMonth = await monei.billsRecord.getBills({
    startDate: '2024-02-01',
    endDate: '2024-02-29'
  });

  console.log(`Payments in February: ${thisMonth.pagination.total}`);

  // Calculate total spent
  const totalSpent = thisMonth.data.reduce((sum, p) => 
    p.status === 'successful' ? sum + p.totalAmount : sum, 0
  );

  console.log(`Total Spent: ₦${totalSpent.toLocaleString()}`);

  // Group by category
  const byCategory = {};
  thisMonth.data.forEach(p => {
    if (p.status === 'successful') {
      byCategory[p.category] = (byCategory[p.category] || 0) + p.totalAmount;
    }
  });

  console.log('\nSpending by Category:');
  Object.entries(byCategory).forEach(([category, amount]) => {
    console.log(`${category}: ₦${amount.toLocaleString()}`);
  });
  ```

  ```python Python theme={null}
  from datetime import datetime, timedelta

  # This month
  this_month = monei.bills_record.get_bills(
      start_date='2024-02-01',
      end_date='2024-02-29'
  )

  print(f'Payments: {this_month.pagination.total}')

  # Total spent
  total_spent = sum(
      p.total_amount for p in this_month.data 
      if p.status == 'successful'
  )

  print(f'Total: ₦{total_spent:,}')

  # By category
  by_category = {}
  for p in this_month.data:
      if p.status == 'successful':
          category = p.category
          by_category[category] = by_category.get(category, 0) + p.total_amount

  print('\nBy Category:')
  for category, amount in by_category.items():
      print(f'{category}: ₦{amount:,}')
  ```
</CodeGroup>

***

## Get Payment Details

Retrieve detailed information about a specific payment.

<CodeGroup>
  ```javascript Node.js theme={null}
  // Get payment by reference
  const payment = await monei.billsRecord.getBillByReference('BILL-ABC123XYZ');

  console.log('Payment Details:');
  console.log('================');
  console.log('Reference:', payment.reference);
  console.log('Status:', payment.status);
  console.log('Biller:', payment.billerName);
  console.log('Category:', payment.category);
  console.log('Customer:', payment.customerName);
  console.log('Customer ID:', payment.customerId);
  console.log('Amount:', payment.amount);
  console.log('Fee:', payment.fee);
  console.log('Total:', payment.totalAmount);
  console.log('Type:', payment.type);
  console.log('Date:', new Date(payment.createdAt).toLocaleString());

  // Show category-specific details
  if (payment.category === 'electricity' && payment.token) {
    console.log('\nElectricity Details:');
    console.log('Token:', payment.token);
    console.log('Units:', payment.units, 'kWh');
    console.log('Meter:', payment.customerId);
  }

  if (payment.category === 'cable_tv' && payment.packageName) {
    console.log('\nCable TV Details:');
    console.log('Package:', payment.packageName);
    console.log('Smartcard:', payment.customerId);
    console.log('Renewal Date:', payment.renewalDate);
  }
  ```

  ```python Python theme={null}
  # Get payment details
  payment = monei.bills_record.get_bill_by_reference('BILL-ABC123XYZ')

  print('Payment Details:')
  print('=' * 20)
  print(f'Reference: {payment.reference}')
  print(f'Status: {payment.status}')
  print(f'Biller: {payment.biller_name}')
  print(f'Category: {payment.category}')
  print(f'Customer: {payment.customer_name}')
  print(f'Amount: ₦{payment.amount}')
  print(f'Fee: ₦{payment.fee}')
  print(f'Total: ₦{payment.total_amount}')
  print(f'Date: {payment.created_at}')

  # Category-specific
  if payment.category == 'electricity' and payment.token:
      print(f'\nToken: {payment.token}')
      print(f'Units: {payment.units} kWh')

  if payment.category == 'cable_tv' and payment.package_name:
      print(f'\nPackage: {payment.package_name}')
      print(f'Smartcard: {payment.customer_id}')
  ```

  ```bash cURL theme={null}
  curl https://api.monei.cc/api/v1/bills/payment/BILL-ABC123XYZ \
    -H "x-api-key: YOUR_API_KEY"
  ```
</CodeGroup>

***

## Spending Analytics

Analyze your bill payment patterns.

<CodeGroup>
  ```javascript Node.js theme={null}
  async function analyzeSpending(startDate, endDate) {
    const payments = await monei.billsRecord.getBills({

      startDate: startDate,
      endDate: endDate,
      status: 'successful',
      limit: 1000
    });
    
    const analytics = {
      totalSpent: 0,
      totalPayments: payments.pagination.total,
      byCategory: {},
      byBiller: {},
      averageAmount: 0,
      largestPayment: null,
      mostFrequentBiller: null
    };
    
    // Process payments
    payments.data.forEach(p => {
      // Total spent
      analytics.totalSpent += p.totalAmount;
      
      // By category
      analytics.byCategory[p.category] = 
        (analytics.byCategory[p.category] || 0) + p.totalAmount;
      
      // By biller
      analytics.byBiller[p.billerName] = {
        count: (analytics.byBiller[p.billerName]?.count || 0) + 1,
        amount: (analytics.byBiller[p.billerName]?.amount || 0) + p.totalAmount
      };
      
      // Largest payment
      if (!analytics.largestPayment || p.totalAmount > analytics.largestPayment.amount) {
        analytics.largestPayment = {
          reference: p.reference,
          biller: p.billerName,
          amount: p.totalAmount,
          date: p.createdAt
        };
      }
    });
    
    // Average
    analytics.averageAmount = analytics.totalSpent / analytics.totalPayments;
    
    // Most frequent
    const billerCounts = Object.entries(analytics.byBiller)
      .sort((a, b) => b[1].count - a[1].count);
    analytics.mostFrequentBiller = billerCounts[0];
    
    // Display
    console.log('Spending Analytics');
    console.log('==================');
    console.log('Total Spent:', `₦${analytics.totalSpent.toLocaleString()}`);
    console.log('Total Payments:', analytics.totalPayments);
    console.log('Average Amount:', `₦${analytics.averageAmount.toFixed(2)}`);
    
    console.log('\nBy Category:');
    Object.entries(analytics.byCategory).forEach(([cat, amt]) => {
      console.log(`  ${cat}: ₦${amt.toLocaleString()}`);
    });
    
    console.log('\nMost Frequent Biller:');
    console.log(`  ${analytics.mostFrequentBiller[0]}`);
    console.log(`  Payments: ${analytics.mostFrequentBiller[1].count}`);
    console.log(`  Total: ₦${analytics.mostFrequentBiller[1].amount.toLocaleString()}`);
    
    console.log('\nLargest Payment:');
    console.log(`  ${analytics.largestPayment.biller}: ₦${analytics.largestPayment.amount.toLocaleString()}`);
    console.log(`  Date: ${new Date(analytics.largestPayment.date).toLocaleDateString()}`);
    
    return analytics;
  }

  // Analyze this month
  await analyzeSpending('2024-02-01', '2024-02-29');
  ```

  ```python Python theme={null}
  async def analyze_spending(start_date, end_date):
      payments = monei.bills_records.get_bills(
          start_date=start_date,
          end_date=end_date,
          status='successful',
          limit=1000
      )
      
      analytics = {
          'total_spent': 0,
          'total_payments': payments.pagination.total,
          'by_category': {},
          'by_biller': {}
      }
      
      # Process
      for p in payments.data:
          analytics['total_spent'] += p.total_amount
          
          # By category
          cat = p.category
          analytics['by_category'][cat] = \
              analytics['by_category'].get(cat, 0) + p.total_amount
          
          # By biller
          biller = p.biller_name
          if biller not in analytics['by_biller']:
              analytics['by_biller'][biller] = {'count': 0, 'amount': 0}
          analytics['by_biller'][biller]['count'] += 1
          analytics['by_biller'][biller]['amount'] += p.total_amount
      
      # Average
      analytics['average'] = analytics['total_spent'] / analytics['total_payments']
      
      # Display
      print('Spending Analytics')
      print('=' * 20)
      print(f"Total Spent: ₦{analytics['total_spent']:,}")
      print(f"Payments: {analytics['total_payments']}")
      print(f"Average: ₦{analytics['average']:.2f}")
      
      print('\nBy Category:')
      for cat, amt in analytics['by_category'].items():
          print(f'  {cat}: ₦{amt:,}')
      
      return analytics

  # Analyze
  await analyze_spending('2024-02-01', '2024-02-29')
  ```
</CodeGroup>

***

## Export History

Export payment history for record-keeping.

<CodeGroup>
  ```javascript Node.js theme={null}
  async function exportToCSV(startDate, endDate) {
    const payments = await monei.billsRecord.getBills({
      startDate: startDate,
      endDate: endDate,
      limit: 1000
    });
    
    // CSV headers
    const headers = [
      'Date',
      'Reference',
      'Biller',
      'Category',
      'Customer',
      'Customer ID',
      'Amount',
      'Fee',
      'Total',
      'Status'
    ];
    
    // CSV rows
    const rows = payments.data.map(p => [
      new Date(p.createdAt).toLocaleDateString(),
      p.reference,
      p.billerName,
      p.category,
      p.customerName,
      p.customerId,
      p.amount,
      p.fee,
      p.totalAmount,
      p.status
    ]);
    
    // Combine
    const csv = [
      headers.join(','),
      ...rows.map(row => row.join(','))
    ].join('\n');
    
    // Save to file
    const fs = require('fs');
    fs.writeFileSync('bill-payments.csv', csv);
    
    console.log('Exported', payments.data.length, 'payments to bill-payments.csv');
    
    return csv;
  }

  // Export this month
  await exportToCSV('2024-02-01', '2024-02-29');
  ```

  ```python Python theme={null}
  import csv
  from datetime import datetime

  async def export_to_csv(start_date, end_date):
      payments = monei.bills_record.get_bills(
          start_date=start_date,
          end_date=end_date,
          limit=1000
      )
      
      # Write CSV
      with open('bill-payments.csv', 'w', newline='') as f:
          writer = csv.writer(f)
          
          # Headers
          writer.writerow([
              'Date', 'Reference', 'Biller', 'Category',
              'Customer', 'Customer ID', 'Amount', 'Fee',
              'Total', 'Status'
          ])
          
          # Rows
          for p in payments.data:
              writer.writerow([
                  p.created_at,
                  p.reference,
                  p.biller_name,
                  p.category,
                  p.customer_name,
                  p.customer_id,
                  p.amount,
                  p.fee,
                  p.total_amount,
                  p.status
              ])
      
      print(f'Exported {len(payments.data)} payments')

  # Export
  await export_to_csv('2024-02-01', '2024-02-29')
  ```
</CodeGroup>

***

## Best Practices

<CardGroup cols={2}>
  <Card title="Regular Reviews" icon="calendar">
    Review payment history monthly
  </Card>

  <Card title="Save Receipts" icon="receipt">
    Keep payment references for important bills
  </Card>

  <Card title="Track Spending" icon="chart-line">
    Monitor spending patterns by category
  </Card>

  <Card title="Export Records" icon="download">
    Export history for accounting/tax purposes
  </Card>

  <Card title="Check Failed" icon="circle-xmark">
    Review failed payments and reasons
  </Card>

  <Card title="Reconcile" icon="check-double">
    Match payments with bank statements
  </Card>
</CardGroup>

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Overview" icon="circle-info" href="/bill-payments/overview">
    Bill payments introduction
  </Card>

  <Card title="Discovery" icon="magnifying-glass" href="/bill-payments/discovery">
    Browse available billers
  </Card>

  <Card title="Validation" icon="check" href="/bill-payments/validation">
    Validate customer details
  </Card>

  <Card title="Payments" icon="credit-card" href="/bill-payments/payments">
    Make bill payments
  </Card>
</CardGroup>
