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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
# 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

```json

{

  "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)

```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": [

      {

        "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)**

```json

{

  "status": "error",

  "message": "Validation failed",

  "errors": {

    "student_id": "Student ID is required",

    "amount": "Amount must be greater than zero"

  }

}

```

**Student Not Found (HTTP 404)**

```json

{

  "status": "error",

  "message": "Student not found"

}

```

**Teller Not Found (HTTP 404)**

```json

{

  "status": "error",

  "message": "Teller number not found"

}

```

**Amount Exceeds Unreconciled (HTTP 400)**

```json

{

  "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)**

```json

{

  "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)**

```json

{

  "status": "error",

  "message": "Invalid API key"

}

```

**Invalid Content-Type (HTTP 400)**

```json

{

  "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:**

```json

{

  "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:**

```json

{

  "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:**

```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"

}



// Server error

{

  "status": "error",

  "message": "Error generating receipt: [error details]"

}

```

**Example Requests:**

**cURL:**
```bash

# 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

<?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):**
```javascript

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:**
```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

```bash

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

<?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)

```javascript

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

```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`:

```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