Spaces:
Running
Running
File size: 10,807 Bytes
e31284f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 | # 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
|