# 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