From 5fa2bf780d2c27987be1881b0ec61213907775a6 Mon Sep 17 00:00:00 2001 From: Shihaam Abdul Rahman Date: Mon, 9 Dec 2024 08:45:34 +0500 Subject: [PATCH] stop giving false json --- api.py | 117 +++++++++++++++++++++++++++++++++------------------------ 1 file changed, 68 insertions(+), 49 deletions(-) diff --git a/api.py b/api.py index d4e7b2d..896fe21 100755 --- a/api.py +++ b/api.py @@ -69,67 +69,86 @@ def compare_amounts(amount1, amount2): """Compare two amount strings as Decimal objects.""" return Decimal(amount1) == Decimal(amount2) +@app.errorhandler(400) +def bad_request(error): + return jsonify({"success": False, "message": "Invalid request: Malformed JSON"}), 400 + +@app.errorhandler(500) +def internal_error(error): + return jsonify({"success": False, "message": "Internal server error"}), 500 + @app.route('/verify-payment', methods=['POST']) def verify_payment(): - data = request.json - benef_name = data.get('benefName', '').strip() - account_no = data.get('accountNo') - abs_amount = data.get('absAmount') - time_str = data.get('time') - - if not all([abs_amount, time_str]): - 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 - try: - request_time = datetime.strptime(time_str, "%Y-%m-%d %H:%M") - except ValueError: - return jsonify({"success": False, "message": "Invalid time format"}), 400 + if not request.is_json: + return jsonify({"success": False, "message": "Request must be JSON"}), 400 + + data = request.get_json() + if data is None: + return jsonify({"success": False, "message": "Invalid JSON format"}), 400 + + benef_name = data.get('benefName', '').strip() if data.get('benefName') else '' + account_no = data.get('accountNo') + abs_amount = data.get('absAmount') + time_str = data.get('time') - 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 + if not all([abs_amount, time_str]): + return jsonify({"success": False, "message": "Missing required parameters"}), 400 - # First, try to verify with benefName if provided - if benef_name: - verified, tx_data = verify_transaction(benef_name, abs_amount, request_time, tx_data_list) - if verified: - return jsonify({ - "success": True, - "message": "Payment verified using beneficiary name", - "transaction": get_transaction_details(tx_data) - }) + if not benef_name and not account_no: + return jsonify({"success": False, "message": "Either benefName or accountNo must be provided"}), 400 - # If benefName verification failed or wasn't provided, try with accountNo - if account_no: - fetched_name = fetch_account_name(account_no) - if fetched_name: - verified, tx_data = verify_transaction(fetched_name, abs_amount, request_time, tx_data_list) + 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)}"}), 500 + except json.JSONDecodeError as e: + return jsonify({"success": False, "message": f"Error parsing tx.sh output: {str(e)}"}), 500 + + # First, try to verify with benefName if provided + if benef_name: + verified, tx_data = verify_transaction(benef_name, abs_amount, request_time, tx_data_list) if verified: return jsonify({ "success": True, - "message": "Payment verified using account number", + "message": "Payment verified using beneficiary name", "transaction": get_transaction_details(tx_data) }) - # If both verifications fail - return jsonify({"success": False, "message": "Transaction not found, contact support"}) + # If benefName verification failed or wasn't provided, try with accountNo + if account_no: + fetched_name = fetch_account_name(account_no) + if fetched_name: + verified, tx_data = verify_transaction(fetched_name, abs_amount, request_time, tx_data_list) + if verified: + return jsonify({ + "success": True, + "message": "Payment verified using account number", + "transaction": get_transaction_details(tx_data) + }) + + # If both verifications fail + return jsonify({"success": False, "message": "Transaction not found, contact support"}) + + except Exception as e: + app.logger.error(f"Unexpected error: {str(e)}") + return jsonify({"success": False, "message": "Internal server error"}), 500 if __name__ == '__main__': debug_mode = os.getenv('APP_DEBUG', 'False').lower() in ('true', '1', 't')