Spaces:
Running
Running
| # Payment Processing API - Implementation Guide | |
| ## π― Overview | |
| This implementation extends the existing EasyPay application to support external payment initiation via a secure JSON API, without breaking or altering any existing internal payment workflows. | |
| ## β What Was Implemented | |
| ### 1. **Core Architecture** | |
| - **`includes/PaymentProcessor.php`**: Encapsulates all payment processing logic | |
| - Single source of truth for payment operations | |
| - Used by both web UI and API | |
| - Maintains all existing business rules | |
| - Atomic transactions with rollback on error | |
| - **`includes/ApiValidator.php`**: Handles API validation and security | |
| - Request validation (method, headers, content-type) | |
| - API key authentication (optional) | |
| - Input sanitization | |
| - Business rule validation | |
| ### 2. **API Endpoint** | |
| - **`api/payments/process.php`**: Main API endpoint | |
| - Accepts JSON POST requests | |
| - Validates all inputs | |
| - Reuses PaymentProcessor for business logic | |
| - Returns structured JSON responses | |
| - Logs all API requests | |
| ### 3. **Configuration** | |
| - **`config/api_config.php`**: API settings | |
| - API key management | |
| - Authentication toggle | |
| - Logging configuration | |
| - CORS settings | |
| ### 4. **Documentation & Testing** | |
| - **`api/API_DOCUMENTATION.md`**: Comprehensive API documentation | |
| - **`api/test.html`**: Interactive API testing tool | |
| - **`api/.htaccess`**: Clean URLs and security headers | |
| ## π File Structure | |
| ``` | |
| easypay/ | |
| βββ api/ | |
| β βββ payments/ | |
| β β βββ process.php # Main API endpoint | |
| β βββ .htaccess # URL routing & security | |
| β βββ API_DOCUMENTATION.md # Full API docs | |
| β βββ test.html # API testing tool | |
| βββ config/ | |
| β βββ api_config.php # API configuration | |
| βββ includes/ | |
| β βββ PaymentProcessor.php # Core payment logic | |
| β βββ ApiValidator.php # API validation | |
| βββ logs/ | |
| β βββ api.log # API request logs (auto-created) | |
| βββ db_config.php # Database connection | |
| βββ index.php # Web UI (unchanged) | |
| βββ process_payment.php # Web payment handler (unchanged) | |
| βββ ajax_handlers.php # AJAX endpoints (unchanged) | |
| ``` | |
| ## π Quick Start | |
| ### 1. Access the API | |
| **Endpoint URL:** | |
| ``` | |
| POST http://your-domain.com/easypay/api/payments/process | |
| ``` | |
| ### 2. Test the API | |
| Open the testing tool in your browser: | |
| ``` | |
| http://your-domain.com/easypay/api/test.html | |
| ``` | |
| ### 3. Send a Request | |
| **Example Request:** | |
| ```bash | |
| curl -X POST http://localhost/easypay/api/payments/process \ | |
| -H "Content-Type: application/json" \ | |
| -d '{ | |
| "student_id": "000001234567890123", | |
| "teller_no": "1234567890", | |
| "amount": 50000 | |
| }' | |
| ``` | |
| **Example Response:** | |
| ```json | |
| { | |
| "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": [...] | |
| } | |
| } | |
| ``` | |
| ## π Security Configuration | |
| ### Enable API Key Authentication | |
| 1. Edit `config/api_config.php`: | |
| ```php | |
| // Enable authentication | |
| define('API_AUTH_ENABLED', true); | |
| // Add your API keys | |
| define('API_KEYS', [ | |
| 'your-secret-key-123' => 'External System 1', | |
| 'another-secret-key-456' => 'Mobile App' | |
| ]); | |
| ``` | |
| 2. Include API key in requests: | |
| ```bash | |
| curl -X POST http://localhost/easypay/api/payments/process \ | |
| -H "Content-Type: application/json" \ | |
| -H "Authorization: Bearer your-secret-key-123" \ | |
| -d '{...}' | |
| ``` | |
| ## β¨ Key Features | |
| ### β Backward Compatibility | |
| - **Zero changes** to existing web UI | |
| - **Zero changes** to existing payment logic | |
| - **Zero changes** to database schema | |
| - Web and API use the same payment processor | |
| ### β Validation & Security | |
| - β Student ID validation (must exist and be active) | |
| - β Teller number validation (must exist with unreconciled amount) | |
| - β Amount validation (positive, within limits) | |
| - β Duplicate prevention (one payment per student per day) | |
| - β SQL injection protection (prepared statements) | |
| - β Input sanitization | |
| - β Optional API key authentication | |
| - β Transaction integrity (atomic operations) | |
| ### β Automatic Payment Allocation | |
| - Fetches all outstanding fees for the student | |
| - Sorts fees by session/term (oldest first) | |
| - Allocates payment automatically | |
| - Fully settles fees before moving to next | |
| - Partial settlement of last fee if needed | |
| ### β Comprehensive Logging | |
| - All API requests logged to `logs/api.log` | |
| - Includes timestamp, IP, request, response, status | |
| - Can be disabled in config | |
| ### β Error Handling | |
| - Structured error responses | |
| - Appropriate HTTP status codes | |
| - Detailed validation errors | |
| - Transaction rollback on failure | |
| ## π§ͺ Testing Checklist | |
| ### Test Cases | |
| 1. **β Valid Payment** | |
| - Send valid student_id, teller_no, amount | |
| - Expect HTTP 201 with payment details | |
| 2. **β Invalid Student** | |
| - Send non-existent student_id | |
| - Expect HTTP 404 "Student not found" | |
| 3. **β Invalid Teller** | |
| - Send non-existent teller_no | |
| - Expect HTTP 404 "Teller number not found" | |
| 4. **β Excessive Amount** | |
| - Send amount > unreconciled amount | |
| - Expect HTTP 400 "Amount exceeds..." | |
| 5. **β Duplicate Payment** | |
| - Send two payments for same student on same day | |
| - Expect HTTP 500 with duplicate error | |
| 6. **β Missing Fields** | |
| - Send request without required fields | |
| - Expect HTTP 400 with validation errors | |
| 7. **β Invalid JSON** | |
| - Send malformed JSON | |
| - Expect HTTP 400 "Invalid JSON" | |
| 8. **β Wrong Content-Type** | |
| - Send without application/json header | |
| - Expect HTTP 400 "Invalid Content-Type" | |
| 9. **β Invalid API Key** (if auth enabled) | |
| - Send with wrong API key | |
| - Expect HTTP 401 "Invalid API key" | |
| ## π Database Impact | |
| The API writes to the same tables as the web UI: | |
| | Table | Purpose | | |
| |-------|---------| | |
| | `tb_account_school_fee_payments` | Individual fee payments | | |
| | `tb_account_school_fee_sum_payments` | Aggregated payments | | |
| | `tb_account_student_payments` | Cumulative payment tracking | | |
| | `tb_account_payment_registers` | Receipt records | | |
| | `tb_student_logistics` | Outstanding balance updates | | |
| **All operations are atomic** - if any step fails, all changes are rolled back. | |
| ## π Monitoring & Debugging | |
| ### View API Logs | |
| ```bash | |
| # View last 20 API requests | |
| tail -n 20 logs/api.log | |
| # Watch logs in real-time | |
| tail -f logs/api.log | |
| ``` | |
| ### Enable Debug Mode | |
| In `api/payments/process.php`, change: | |
| ```php | |
| error_reporting(E_ALL); | |
| ini_set('display_errors', 1); // Enable for debugging | |
| ``` | |
| ## π οΈ Troubleshooting | |
| ### "Database connection failed" | |
| - Check `db_config.php` credentials | |
| - Ensure MySQL is running | |
| - Verify network connectivity | |
| ### "Student not found" | |
| - Verify student exists in `tb_student_registrations` | |
| - Check `admission_status = 'Active'` | |
| ### "Teller number not found" | |
| - Verify teller in `tb_account_bank_statements` | |
| - Check description format (teller is last word) | |
| ### "No outstanding fees found" | |
| - Check `tb_account_receivables` for student | |
| - Verify fees have outstanding balance | |
| ### API returns HTML instead of JSON | |
| - Check for PHP errors in the file | |
| - Enable error logging to see issues | |
| - Verify all required files are present | |
| ## π Implementation Notes | |
| ### Design Decisions | |
| 1. **PaymentProcessor Class**: Extracted payment logic into a reusable class to ensure both web and API use identical business rules. | |
| 2. **Automatic Fee Selection**: The API automatically fetches and allocates to outstanding fees, simplifying the external system's integration. | |
| 3. **Source Tracking**: Payments are marked with `source = 'api'` for audit purposes. | |
| 4. **Current Date**: API uses current date for payments (not configurable via API for security). | |
| 5. **Optional Authentication**: API key auth is optional to allow easy testing and gradual rollout. | |
| ### Future Enhancements | |
| - Rate limiting per API key | |
| - Webhook notifications for payment status | |
| - Batch payment processing | |
| - Payment reversal endpoint | |
| - Custom payment date (with authorization) | |
| - IP whitelisting | |
| ## π Student API Endpoints | |
| ### 1. **Get Last Payment Receipt Image** | |
| **Endpoint:** `GET /api/students/last_receipt` | |
| **Description:** Returns the receipt image (PNG) of the last payment made by a student. | |
| **Parameters:** | |
| - `student_id` (required): The student's unique ID | |
| **Example Request:** | |
| ```bash | |
| curl -X GET "http://localhost/easypay/api/students/last_receipt?student_id=000001234567890123" \ | |
| --output receipt.png | |
| ``` | |
| **Success Response:** | |
| - **Content-Type:** `image/png` | |
| - **Body:** Binary PNG image data | |
| **Error Responses:** | |
| ```json | |
| // 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" | |
| } | |
| ``` | |
| ### 2. **Get Payment Status** | |
| **Endpoint:** `GET /api/students/payment_status` | |
| **Description:** Returns payment status for a specific term. | |
| **Parameters:** | |
| - `student_id` (required): The student's unique ID | |
| - `academic_session` (required): Academic session (e.g., 2025) | |
| - `term` (required): Term number (e.g., 1, 2, 3) | |
| ### 3. **Get Student Balance** | |
| **Endpoint:** `GET /api/students/balance` | |
| **Description:** Returns the current outstanding balance for a student. | |
| **Parameters:** | |
| - `student_id` (required): The student's unique ID | |
| ### 4. **Get Student Invoice** | |
| **Endpoint:** `GET /api/students/invoice` | |
| **Description:** Returns detailed invoice information for a student. | |
| **Parameters:** | |
| - `student_id` (required): The student's unique ID | |
| - `academic_session` (optional): Filter by academic session | |
| - `term` (optional): Filter by term | |
| ## π Usage Examples | |
| See `api/API_DOCUMENTATION.md` for detailed examples in: | |
| - cURL | |
| - PHP | |
| - JavaScript (Fetch API) | |
| - Python | |
| ## π Support | |
| For issues or questions: | |
| 1. Check the API documentation | |
| 2. Review the logs in `logs/api.log` | |
| 3. Use the test tool at `api/test.html` | |
| 4. Contact your system administrator | |
| ## π License | |
| Internal use only - ARPS School Management System | |
| --- | |
| **Version:** 1.0 | |
| **Date:** 2026-01-09 | |
| **Author:** Senior PHP Backend Engineer | |