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|
+
# TODO: Implement payment endpoints
|
| 3 |
+
|
| 4 |
+
from fastapi import FastAPI, Request, HTTPException
|
| 5 |
+
from pydantic import BaseModel
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
import random
|
| 8 |
+
import uvicorn
|
| 9 |
+
import logging
|
| 10 |
+
from typing import Dict, Any
|
| 11 |
+
|
| 12 |
+
logging.basicConfig(level=logging.INFO)
|
| 13 |
+
logger = logging.getLogger(__name__)
|
| 14 |
+
|
| 15 |
+
app = FastAPI(
|
| 16 |
+
title="Invoice Payment API",
|
| 17 |
+
description="Payment processing simulation for invoice automation",
|
| 18 |
+
version="1.0.0"
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
TRANSACTIONS: Dict[str, Dict[str, Any]] = {}
|
| 22 |
+
PAYMENT_METRICS = {
|
| 23 |
+
'total_transactions': 0,
|
| 24 |
+
'successful_payments': 0,
|
| 25 |
+
'failed_payments': 0,
|
| 26 |
+
'cancelled_payments': 0,
|
| 27 |
+
'last_transaction_time': None
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class PaymentRequest(BaseModel):
|
| 32 |
+
order_id: str
|
| 33 |
+
customer_name: str
|
| 34 |
+
amount: float
|
| 35 |
+
currency: str = 'USD'
|
| 36 |
+
method: str = 'bank_transfer'
|
| 37 |
+
recipient_account: str = 'default_account'
|
| 38 |
+
due_date: str
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class PaymentResponse(BaseModel):
|
| 42 |
+
transaction_id: str
|
| 43 |
+
status: str
|
| 44 |
+
message: str
|
| 45 |
+
processed_at: str
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
@app.get("/")
|
| 49 |
+
async def root():
|
| 50 |
+
return {'message': 'Welcome to the Invoice Payment API', 'version': '1.0.0'}
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
@app.get("/health")
|
| 54 |
+
async def health_check():
|
| 55 |
+
return {
|
| 56 |
+
'status': 'healthy',
|
| 57 |
+
'timestamp': datetime.utcnow().isoformat(),
|
| 58 |
+
'uptime': 'OK'
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
@app.post("/initiate_payment")
|
| 63 |
+
async def initiate_payment(payment_request: PaymentRequest):
|
| 64 |
+
transaction_id = f"txn_{int(datetime.utcnow().timestamp())}_{random.randint(1000,9999)}"
|
| 65 |
+
PAYMENT_METRICS['total_transactions'] += 1
|
| 66 |
+
PAYMENT_METRICS['last_transaction_time'] = datetime.utcnow().isoformat()
|
| 67 |
+
|
| 68 |
+
success_chance = 0.85
|
| 69 |
+
if random.random() < success_chance:
|
| 70 |
+
status = 'SUCCESS'
|
| 71 |
+
message = f"Payment of {payment_request.amount} {payment_request.currency} successful."
|
| 72 |
+
PAYMENT_METRICS['successful_payments'] += 1
|
| 73 |
+
else:
|
| 74 |
+
status = 'FAILED'
|
| 75 |
+
message = 'Payment failed due to simulated gateway error.'
|
| 76 |
+
PAYMENT_METRICS['failed_payments'] += 1
|
| 77 |
+
|
| 78 |
+
transaction_data = {
|
| 79 |
+
'transaction_id': transaction_id,
|
| 80 |
+
'order_id': payment_request.order_id,
|
| 81 |
+
'customer_name': payment_request.customer_name,
|
| 82 |
+
'amount': payment_request.amount,
|
| 83 |
+
'currency': payment_request.currency,
|
| 84 |
+
'method': payment_request.method,
|
| 85 |
+
'recipient_account': payment_request.recipient_account,
|
| 86 |
+
'status': status,
|
| 87 |
+
'message': message,
|
| 88 |
+
'created_at': datetime.utcnow().isoformat(),
|
| 89 |
+
'updated_at': datetime.utcnow().isoformat()
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
TRANSACTIONS[transaction_id] = transaction_data
|
| 93 |
+
logger.info(f"Processed payment transaction {transaction_id} with status: {status}")
|
| 94 |
+
|
| 95 |
+
return PaymentResponse(
|
| 96 |
+
transaction_id=transaction_id,
|
| 97 |
+
status=status,
|
| 98 |
+
message=message,
|
| 99 |
+
processed_at=transaction_data['updated_at']
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
@app.get("/transaction/{transaction_id}")
|
| 104 |
+
async def get_transaction_status(transaction_id: str):
|
| 105 |
+
transaction = TRANSACTIONS.get(transaction_id)
|
| 106 |
+
if not transaction:
|
| 107 |
+
raise HTTPException(status_code=404, detail="Transaction not found")
|
| 108 |
+
return transaction
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
@app.post("/cancel_payment/{transaction_id}")
|
| 112 |
+
async def cancel_payment(transaction_id: str):
|
| 113 |
+
transaction = TRANSACTIONS.get(transaction_id)
|
| 114 |
+
if not transaction:
|
| 115 |
+
raise HTTPException(status_code=400, detail="Cannot cancel a non-existent payment")
|
| 116 |
+
|
| 117 |
+
if transaction['status'] in ['SUCCESS', 'FAILED']:
|
| 118 |
+
raise HTTPException(status_code=400, detail="Cannot cancel a completed payment")
|
| 119 |
+
|
| 120 |
+
transaction['status'] = 'CANCELLED'
|
| 121 |
+
transaction['updated_at'] = datetime.utcnow().isoformat()
|
| 122 |
+
PAYMENT_METRICS['cancelled_payments'] += 1
|
| 123 |
+
logger.info(f"Cancelled payment transaction: {transaction_id}")
|
| 124 |
+
return {
|
| 125 |
+
'transaction_id': transaction_id,
|
| 126 |
+
'status': 'CANCELLED',
|
| 127 |
+
'message': 'Payment has been cancelled successfully'
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
@app.get("/payment_methods")
|
| 132 |
+
async def get_payment_methods():
|
| 133 |
+
return {
|
| 134 |
+
'available_methods': [
|
| 135 |
+
'bank_transfer',
|
| 136 |
+
'credit_card',
|
| 137 |
+
'paypal',
|
| 138 |
+
'upi',
|
| 139 |
+
'crypto'
|
| 140 |
+
],
|
| 141 |
+
'default_method': 'bank_transfer'
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
@app.get("/metrics")
|
| 146 |
+
async def get_metrics():
|
| 147 |
+
return {
|
| 148 |
+
'metrics': PAYMENT_METRICS,
|
| 149 |
+
'active_transactions': len(TRANSACTIONS)
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
if __name__ == "__main__":
|
| 154 |
+
uvicorn.run(app, host="0.0.0.0", port=8001)
|