php / easypay-api /api /API_DOCUMENTATION.md
kingkay000's picture
Upload 25 files
e31284f verified

Payment Processing API Documentation

Overview

The Payment Processing API allows external systems to initiate student fee payments securely via JSON requests. The API uses the same internal payment processing logic as the web application, ensuring consistency and reliability.

Base URL

http://your-domain.com/easypay/api/

Authentication

API Key (Optional)

If API authentication is enabled, include an API key in the request header:

Authorization: Bearer YOUR_API_KEY

To enable API authentication:

  1. Edit config/api_config.php
  2. Set API_AUTH_ENABLED to true
  3. Add your API keys to the API_KEYS array

Endpoint

Process Payment

POST /api/payments/process

Processes a student fee payment using a bank teller number.

Request Headers

Content-Type: application/json
Authorization: Bearer YOUR_API_KEY (if authentication is enabled)

Request Body

{
  "student_id": "string|integer",
  "teller_no": "string",
  "amount": number
}

Field Descriptions:

Field Type Required Description
student_id string/integer Yes The unique ID of the student from tb_student_registrations
teller_no string Yes The teller number from the bank statement (must exist in tb_account_bank_statements)
amount number Yes The amount to allocate to student fees (must be positive and not exceed unreconciled amount)

Success Response (HTTP 201)

{
  "status": "success",
  "message": "Payment processed successfully",
  "data": {
    "student_id": "000001234567890123",
    "teller_no": "1234567890",
    "amount": 50000.00,
    "payment_id": "000001234567890123202420260109",
    "receipt_no": "STU001202420260109",
    "payment_date": "2026-01-09",
    "fees_settled": [
      {
        "fee_description": "Tuition Fee",
        "session": "2024",
        "term": "1",
        "amount": 30000.00
      },
      {
        "fee_description": "Development Levy",
        "session": "2024",
        "term": "1",
        "amount": 20000.00
      }
    ]
  }
}

Error Responses

Validation Error (HTTP 400)

{
  "status": "error",
  "message": "Validation failed",
  "errors": {
    "student_id": "Student ID is required",
    "amount": "Amount must be greater than zero"
  }
}

Student Not Found (HTTP 404)

{
  "status": "error",
  "message": "Student not found"
}

Teller Not Found (HTTP 404)

{
  "status": "error",
  "message": "Teller number not found"
}

Amount Exceeds Unreconciled (HTTP 400)

{
  "status": "error",
  "message": "Amount exceeds unreconciled amount on teller",
  "errors": {
    "amount": "Requested amount (60,000.00) exceeds available unreconciled amount (50,000.00)"
  }
}

Duplicate Payment (HTTP 400)

{
  "status": "error",
  "message": "Internal server error",
  "error_detail": "A payment for this student has already been registered on this date (2026-01-09)"
}

Unauthorized (HTTP 401)

{
  "status": "error",
  "message": "Invalid API key"
}

Invalid Content-Type (HTTP 400)

{
  "status": "error",
  "message": "Invalid Content-Type. Expected application/json"
}

Server Error (HTTP 500)

{ "status": "error", "message": "Internal server error" }


### Student Information Endpoints

#### 1. Get Outstanding Balance

**GET** `/api/students/balance`

Fetches a student's total outstanding balance and a breakdown of unpaid fees.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `student_id` | string | Yes | The ID of the student |

**Success Response:**

```json
{
  "status": "success",
  "data": {
    "student_id": "000001234567890123",
    "currency": "NGN",
    "total_outstanding": 50000,
    "breakdown": [
      {
        "fee_id": "...",
        "fee_description": "Tuition Fee",
        "academic_session": "2024",
        "term_of_session": "1",
        "amount_billed": 100000,
        "amount_paid": 50000,
        "outstanding_amount": 50000
      }
    ]
  }
}

2. Get Term Invoice

GET /api/students/invoice

Fetches the breakdown of fees billed to a student for a specific term and session.

Parameters:

Parameter Type Required Description
student_id string Yes The ID of the student
academic_session string Yes The accounting year (e.g. "2024")
term string Yes The term number (e.g. "1")

Success Response:

{
  "status": "success",
  "data": {
    "student_id": "...",
    "academic_session": "2024",
    "term": "1",
    "items": [
      {
        "description": "Tuition Fee",
        "amount_billed": 100000,
        "amount_paid": 100000,
        "balance": 0
      }
    ]
  }
}

3. Get Term Payment Status

GET /api/students/payment_status

Gets a copy of the payment status for a term, including summary and transaction history.

Parameters:

Parameter Type Required Description
student_id string Yes The ID of the student
academic_session string Yes The accounting year
term string Yes The term number

Success Response:

{
  "status": "success",
  "data": {
    "summary": {
      "total_billed": 150000,
      "total_paid": 100000,
      "outstanding": 50000
    },
    "transactions": [
      {
        "payment_date": "2026-01-15",
        "amount": 50000,
        "transaction_id": "...",
        "payment_ref": "..."
      }
    ]
  }
}

4. Get Last Payment Receipt Image

GET /api/students/last_receipt

Returns the receipt image (PNG format) of the most recent payment made by a student.

Parameters:

Parameter Type Required Description
student_id string Yes The ID of the student

Success Response:

  • Content-Type: image/png
  • Body: Binary PNG image data
  • The image can be saved directly to a file or displayed in an application

Error Responses:

// Student ID missing
{
  "status": "error",
  "message": "Student ID is required"
}

// Student not found
{
  "status": "error",
  "message": "Student not found or inactive"
}

// No payment records
{
  "status": "error",
  "message": "No payment records found for this student"
}

// Server error
{
  "status": "error",
  "message": "Error generating receipt: [error details]"
}

Example Requests:

cURL:

# Download receipt to file
curl -X GET "http://your-domain.com/easypay/api/students/last_receipt?student_id=000001234567890123" \
  --output receipt.png

# With API authentication
curl -X GET "http://your-domain.com/easypay/api/students/last_receipt?student_id=000001234567890123" \
  -H "Authorization: Bearer your-api-key-here" \
  --output receipt.png

PHP:

<?php
$studentId = '000001234567890123';
$url = "http://your-domain.com/easypay/api/students/last_receipt?student_id={$studentId}";

$context = stream_context_create([
    'http' => [
        'header' => 'Authorization: Bearer your-api-key-here'
    ]
]);

$imageData = file_get_contents($url, false, $context);

if ($imageData !== false) {
    // Save to file
    file_put_contents('receipt.png', $imageData);
    
    // Or display in browser
    header('Content-Type: image/png');
    echo $imageData;
} else {
    echo "Error fetching receipt";
}
?>

JavaScript (Fetch API):

const studentId = '000001234567890123';
const url = `http://your-domain.com/easypay/api/students/last_receipt?student_id=${studentId}`;

fetch(url, {
  headers: {
    'Authorization': 'Bearer your-api-key-here'
  }
})
.then(response => {
  if (response.ok) {
    return response.blob();
  } else {
    return response.json().then(err => {
      throw new Error(err.message);
    });
  }
})
.then(blob => {
  // Create download link
  const url = window.URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = 'receipt.png';
  a.click();
  
  // Or display in img tag
  // document.getElementById('receiptImage').src = url;
})
.catch(error => console.error('Error:', error));

Python:

import requests

student_id = '000001234567890123'
url = f'http://your-domain.com/easypay/api/students/last_receipt?student_id={student_id}'

headers = {
    'Authorization': 'Bearer your-api-key-here'
}

response = requests.get(url, headers=headers)

if response.status_code == 200:
    # Save to file
    with open('receipt.png', 'wb') as f:
        f.write(response.content)
    print("Receipt downloaded successfully")
else:
    # Handle error
    error = response.json()
    print(f"Error: {error['message']}")

Payment Allocation Logic

The API automatically allocates payments using the following rules:

  1. Automatic Fee Selection: The system fetches all outstanding fees for the student
  2. Oldest First: Fees are sorted by academic session (ascending), then term (ascending)
  3. Full Settlement Priority: Each fee is fully settled before moving to the next
  4. Partial Settlement: If the payment amount runs out, the last fee is partially settled
  5. Transaction Integrity: All database operations are wrapped in a transaction (all-or-nothing)

Example

If a student has these outstanding fees:

  • 2024 Term 1 Tuition: ₦30,000
  • 2024 Term 2 Tuition: ₦30,000
  • 2024 Term 3 Tuition: ₦30,000

And you send a payment of ₦50,000:

  • 2024 Term 1: Fully settled (₦30,000)
  • 2024 Term 2: Partially settled (₦20,000)
  • 2024 Term 3: Not settled

Validation Rules

Student Validation

  • Student ID must exist in tb_student_registrations
  • Student must have admission_status = 'Active'
  • Student must have outstanding fees

Teller Validation

  • Teller number must exist in tb_account_bank_statements
  • Teller must have unreconciled amount > 0
  • The teller number is extracted as the last word in the description field

Amount Validation

  • Amount must be a positive number
  • Amount must not exceed the unreconciled amount on the teller
  • Amount must not be zero or negative

Duplicate Prevention

  • Only one payment per student per day is allowed
  • This prevents accidental duplicate submissions

Example Requests

cURL

curl -X POST http://your-domain.com/easypay/api/payments/process \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer your-api-key-here" \
  -d '{
    "student_id": "000001234567890123",
    "teller_no": "1234567890",
    "amount": 50000
  }'

PHP

<?php
$url = 'http://your-domain.com/easypay/api/payments/process';

$data = [
    'student_id' => '000001234567890123',
    'teller_no' => '1234567890',
    'amount' => 50000
];

$options = [
    'http' => [
        'header' => [
            'Content-Type: application/json',
            'Authorization: Bearer your-api-key-here'
        ],
        'method' => 'POST',
        'content' => json_encode($data)
    ]
];

$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
$result = json_decode($response, true);

if ($result['status'] === 'success') {
    echo "Payment processed: " . $result['data']['payment_id'];
} else {
    echo "Error: " . $result['message'];
}
?>

JavaScript (Fetch API)

const url = 'http://your-domain.com/easypay/api/payments/process';

const data = {
  student_id: '000001234567890123',
  teller_no: '1234567890',
  amount: 50000
};

fetch(url, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer your-api-key-here'
  },
  body: JSON.stringify(data)
})
.then(response => response.json())
.then(result => {
  if (result.status === 'success') {
    console.log('Payment processed:', result.data.payment_id);
  } else {
    console.error('Error:', result.message);
  }
})
.catch(error => console.error('Request failed:', error));

Python

import requests
import json

url = 'http://your-domain.com/easypay/api/payments/process'

headers = {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer your-api-key-here'
}

data = {
    'student_id': '000001234567890123',
    'teller_no': '1234567890',
    'amount': 50000
}

response = requests.post(url, headers=headers, json=data)
result = response.json()

if result['status'] == 'success':
    print(f"Payment processed: {result['data']['payment_id']}")
else:
    print(f"Error: {result['message']}")

Database Tables Affected

The API writes to the same tables as the web application:

  1. tb_account_school_fee_payments - Individual fee payment records
  2. tb_account_school_fee_sum_payments - Aggregated payment records
  3. tb_account_student_payments - Cumulative payment tracking
  4. tb_account_payment_registers - Receipt records
  5. tb_student_logistics - Student outstanding balance updates

Logging

API requests are logged to logs/api.log (if enabled in config).

Each log entry includes:

  • Timestamp
  • Client IP address
  • Request data
  • Response data
  • HTTP status code

To enable/disable logging, edit config/api_config.php:

define('API_LOG_ENABLED', true);

Security Considerations

  1. HTTPS Required: Always use HTTPS in production to encrypt API keys and payment data
  2. API Key Management: Store API keys securely and rotate them regularly
  3. IP Whitelisting: Consider restricting API access to specific IP addresses
  4. Rate Limiting: Implement rate limiting to prevent abuse (future enhancement)
  5. Input Validation: All inputs are validated and sanitized before processing
  6. SQL Injection Protection: All database queries use prepared statements
  7. Transaction Integrity: All operations are atomic (all-or-nothing)

Testing

Test with API Authentication Disabled

For initial testing, you can disable API authentication:

  1. Edit config/api_config.php
  2. Set API_AUTH_ENABLED to false
  3. Test without the Authorization header

Test Cases

  1. Valid Payment: Send a valid request with existing student and teller
  2. Invalid Student: Send request with non-existent student ID
  3. Invalid Teller: Send request with non-existent teller number
  4. Excessive Amount: Send amount greater than unreconciled amount
  5. Duplicate Payment: Send two payments for same student on same day
  6. Invalid JSON: Send malformed JSON
  7. Missing Fields: Send request with missing required fields

Troubleshooting

"Database connection failed"

  • Check database credentials in db_config.php
  • Ensure MySQL server is running

"Student not found"

  • Verify student ID exists in tb_student_registrations
  • Check that student has admission_status = 'Active'

"Teller number not found"

  • Verify teller exists in tb_account_bank_statements
  • Check that teller number is the last word in the description field

"Amount exceeds unreconciled amount"

  • Check the unreconciled amount on the teller
  • Reduce the payment amount

"No outstanding fees found"

  • Verify student has unpaid fees in tb_account_receivables

Support

For technical support or questions, contact your system administrator.

Version History

  • v1.0 (2026-01-09): Initial API release
    • Payment processing endpoint
    • JSON request/response format
    • Optional API key authentication
    • Comprehensive validation
    • Transaction logging