php / easypay-api /api /README.md
kingkay000's picture
Upload 25 files
e31284f verified
# 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