103 lines
4.3 KiB
Python
Raw Normal View History

2024-10-19 02:59:48 +05:00
#!/usr/bin/env python3
2024-10-20 01:57:27 +05:00
from decimal import Decimal
2024-10-20 01:10:48 +05:00
import os
from dotenv import load_dotenv
2024-10-19 01:45:56 +05:00
from flask import Flask, request, jsonify
import subprocess
import json
from datetime import datetime, timedelta
2024-10-20 01:10:48 +05:00
load_dotenv() # This will load environment variables from a .env file if it exists
2024-10-19 01:45:56 +05:00
app = Flask(__name__)
2024-10-20 01:10:48 +05:00
def fetch_account_name(account_no):
try:
result = subprocess.run(['./fetchname.sh', account_no], capture_output=True, text=True, check=True)
response = json.loads(result.stdout)
if response.get('success'):
return response.get('accountName')
except (subprocess.CalledProcessError, json.JSONDecodeError) as e:
app.logger.error(f"Error fetching account name: {str(e)}")
return None
def verify_transaction(benef_name, abs_amount, request_time, tx_data_list):
for tx_data in tx_data_list:
required_keys = ['trxDate', 'benefName', 'absAmount']
if not all(key in tx_data for key in required_keys):
continue # Skip this transaction if it's missing required keys
try:
tx_time = datetime.strptime(tx_data['trxDate'], "%Y-%m-%d %H:%M:%S")
time_diff = abs(tx_time - request_time)
tx_benef_name = tx_data['benefName'].strip().lower()
if (tx_benef_name == benef_name.strip().lower() and
2024-10-20 01:57:27 +05:00
compare_amounts(tx_data['absAmount'], abs_amount) and
time_diff <= timedelta(minutes=30)):
return True
except ValueError as e:
app.logger.error(f"Error processing transaction: {str(e)}")
return False
2024-10-20 01:57:27 +05:00
def compare_amounts(amount1, amount2):
"""Compare two amount strings as Decimal objects."""
return Decimal(amount1) == Decimal(amount2)
2024-10-19 01:45:56 +05:00
@app.route('/verify-payment', methods=['POST'])
def verify_payment():
data = request.json
benef_name = data.get('benefName', '').strip()
account_no = data.get('accountNo')
2024-10-19 01:45:56 +05:00
abs_amount = data.get('absAmount')
time_str = data.get('time')
if not all([abs_amount, time_str]):
2024-10-19 01:45:56 +05:00
return jsonify({"success": False, "message": "Missing required parameters"}), 400
if not benef_name and not account_no:
return jsonify({"success": False, "message": "Either benefName or accountNo must be provided"}), 400
2024-10-19 01:45:56 +05:00
try:
request_time = datetime.strptime(time_str, "%Y-%m-%d %H:%M")
except ValueError:
return jsonify({"success": False, "message": "Invalid time format"}), 400
try:
result = subprocess.run(['./tx.sh'], capture_output=True, text=True, check=True)
tx_response = json.loads(result.stdout)
app.logger.debug(f"tx_response: {json.dumps(tx_response, indent=2)}")
if not tx_response.get('success'):
return jsonify({"success": False, "message": f"Error from tx.sh: {tx_response.get('reasonText', 'Unknown error')}"}), 500
tx_data_list = tx_response.get('data', [])
if not tx_data_list:
return jsonify({"success": False, "message": "No transaction data found"}), 404
except subprocess.CalledProcessError as e:
return jsonify({"success": False, "message": f"Error executing tx.sh: {str(e)}", "stderr": e.stderr}), 500
except json.JSONDecodeError as e:
return jsonify({"success": False, "message": f"Error parsing tx.sh output: {str(e)}", "output": result.stdout}), 500
# First, try to verify with benefName if provided
if benef_name and verify_transaction(benef_name, abs_amount, request_time, tx_data_list):
return jsonify({"success": True, "message": "Payment verified using beneficiary name"})
2024-10-19 01:45:56 +05:00
# If benefName verification failed or wasn't provided, try with accountNo
if account_no:
fetched_name = fetch_account_name(account_no)
if fetched_name and verify_transaction(fetched_name, abs_amount, request_time, tx_data_list):
return jsonify({"success": True, "message": "Payment verified using account number"})
2024-10-19 01:45:56 +05:00
# If both verifications fail
2024-10-19 01:45:56 +05:00
return jsonify({"success": False, "message": "Transaction not found, contact support"})
if __name__ == '__main__':
2024-10-19 02:34:50 +05:00
debug_mode = os.getenv('APP_DEBUG', 'False').lower() in ('true', '1', 't')
2024-10-19 02:59:48 +05:00
port = int(os.getenv('PORT', 5000))
app.run(host='0.0.0.0', port=port, debug=debug_mode)