from flask import Flask, request, redirect, abort, session, jsonify from utils import * from FuiouPay import H5Main # from WXPay import WXPay import os, _thread, urllib import logging from logging.handlers import TimedRotatingFileHandler from flask_cors import CORS app = Flask(__name__) app.config['SECRET_KEY'] = os.urandom(24) CORS(app, supports_credentials=True) def setup_logging(): """配置日志系统,按天分割日志文件""" # 创建日志目录 log_dir = "logs" os.makedirs(log_dir, exist_ok=True) # 设置日志格式 log_format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' formatter = logging.Formatter(log_format) # 创建按天轮转的文件处理器 file_handler = TimedRotatingFileHandler( filename=os.path.join(log_dir, 'dpapp.log'), when='midnight', # 每天午夜轮转 interval=1, # 每天一个文件 backupCount=30, # 保留30天的日志 encoding='utf-8' ) file_handler.setFormatter(formatter) file_handler.setLevel(logging.INFO) # 创建控制台处理器 console_handler = logging.StreamHandler() console_handler.setFormatter(formatter) console_handler.setLevel(logging.DEBUG) # 获取根logger并配置 logger = logging.getLogger() logger.setLevel(logging.DEBUG) logger.addHandler(file_handler) logger.addHandler(console_handler) # 初始化日志配置 setup_logging() # 获取当前模块的 logger logger = logging.getLogger(__name__) logger.info(f"DPPayApp started") # 会输出到文件和控制台 @app.route('/queryUserId', methods=['GET']) def queryUserId(): # 获取支付明细 try: code = request.args.get('code') data = query_wx_userid(code) if len(data) <= 11: res = query_wx_fj_info(data) data = res return redirect(f'http://web.jiyuankeshang.com/#/DPpay?user={data}&appid={corpid}&agentid={agentid}') except Exception as e: return {} @app.route('/queryUserIdZY', methods=['GET']) def queryUserIdZY(): # 获取支付明细 try: code = request.args.get('code') data = query_zy_wx_userid(code) if len(data) <= 11: res = query_zy_wx_fj_info(data) data = res return redirect(f'http://web.jiyuankeshang.com/#/DPpay?user={data}&appid={zy_corpid}&agentid={zy_agentid}') except Exception as e: return {} @app.route('/queryUser', methods=['GET']) def queryUserApi(): # 获取支付明细 try: id = request.args.get('user') data = queryUser(id) for item in data['pay_detail']: if 'charge_amount' in item: item['price'] = item.pop('charge_amount') if 'charge_time' in item: item['time'] = item.pop('charge_time') logger.info(f"===================queryUserdata{data}") return data except Exception as e: return {} @app.route('/getPaymentDetails', methods=['GET']) def getPaymentDetails(): try: id = request.args.get('user', '') id = id.replace(" ", "") if not id: logger.info(f"no id") return {} data = query_pay_details(id) for item in data: if item == "amount": continue for detail in data[item]['data']: if 'fukuanshiyou' in detail: detail['name'] = detail.pop('fukuanshiyou') return data except Exception as e: logger.info(f"error{e}") return {} @app.route('/paymentCallBack', methods=['POST']) def paymentCallBack(): # 充值成功后回调 {"pay_amount": 20000, "id": "18515367096"} try: logger.info(f"====================================paymentCallBack=========================================") msg = request.data.decode('UTF-8') logger.info(f"回调参数为===={msg}") msg = eval(msg) logger.info(f"eval参数为===={msg}") if msg['resp_desc'] == '成功': logger.info(f"=================================充值回调SUCCESS==========================================") if msg['mchnt_cd'] == '0001000F7152364': rsa_key = RSA.importKey(open('dg_priv_key.pem').read()) # rsa_key = RSA.importKey(open('E:\YinJian\银建支付对接维护说明\DP\DP-enterprise-wechat-payment-push\dg_priv_key.pem').read()) else: rsa_key = RSA.importKey(open('priv_key.pem').read()) # rsa_key = RSA.importKey(open('E:\YinJian\银建支付对接维护说明\DP\DP-enterprise-wechat-payment-push\priv_key.pem').read()) logger.info(f"msg==={msg['message']}") logger.info(f"rsa_key{rsa_key}") whp = rsa_long_decrypt(rsa_key, msg['message']) logger.info(f"报文已解密{whp}") whp_dict = json.loads(whp) # 打印字典中的所有键 logger.info(f"1111111{whp_dict.keys()}") # 获取'order_id'键的值并取前18个字符 id = whp_dict['order_id'][:18] # 查询机构、分司 res = filter_jdy_ht(id) transaction_id = whp_dict['pay_ssn'] amount = float(whp_dict['order_amt']) order_pay_type = whp_dict['order_pay_type'] # 判断支付类型 if order_pay_type[:2] == "We": pay_type = "微信支付" elif order_pay_type[:3] == "Ali": pay_type = "支付宝支付" elif order_pay_type == "0000000000": pay_type = "云闪付支付" amount = amount / 100 if whp_dict['mchnt_cd'] == '0001000F7152364': payment_items = "驾驶员履约服务费" info1 = {"pay_amount": amount, "id": id, "fs": res[1], "jg": res[0], "name": res[4], "shfid": res[7], "fsfz": res[6], "hphm": res[5], "transaction_id": transaction_id, "payment_items": payment_items, "pay_type": pay_type} logger.info(f"充值回调处理{info1}") _thread.start_new_thread(add_payment_lw, ({"pay_amount": amount, "id": id, "fs": res[1], "jg": res[0], "name": res[4], "shfid": res[7], "fsfz": res[6], "hphm": res[5], "transaction_id": transaction_id, "payment_items": payment_items, "pay_type": pay_type},)) else: payment_items = "承包金" info1 = {"pay_amount": amount, "id": id, "fs": res[1], "jg": res[0], "name": res[4], "shfid": res[7], "fsfz": res[6], "hphm": res[5], "transaction_id": transaction_id, "payment_items": payment_items, "pay_type": pay_type} logger.info(f"充值回调处理{info1}") _thread.start_new_thread(add_payment, ({"pay_amount": amount, "id": id, "fs": res[1], "jg": res[0], "name": res[4], "shfid": res[7], "fsfz": res[6], "hphm": res[5], "transaction_id": transaction_id, "payment_items": payment_items, "pay_type": pay_type},)) return {"code": 200} except Exception as e: return jsonify(error=str(e)), 500 @app.route('/test', methods=['POST']) def test(): # 新增未收付明细 {"pay_amount": 20000, "id": "18515367096"} try: data = request.data.decode("utf-8") logger.info(f"data{data}") return {} except Exception as e: logger.error(f"error{e}") return {} @app.route('/addUnPayment', methods=['POST']) def addno_moneyment(): # 新增未收付明细 {"pay_amount": 20000, "id": "18515367096"} try: data = request.data.decode("utf-8") data = data.replace("null", "None") data = eval(data) data = data['data'] if data['mode_type'] == "DP": res = filter_jdy_ht(data['id_card']) _thread.start_new_thread(add_payment, ({"pay_amount": 0, "id": data['id_card'], "fs": res[1], "jg": res[0], "name": res[4], "shfid": res[7], "fsfz": res[6], "hphm": res[5]}, 1)) return {} else: return {} except Exception as e: logger.error(f"addUnPayment,e{e},res{res}") return {} @app.route('/addPayment', methods=['POST']) def addPayment(): # 新增充值明细 {"pay_amount": 20000, "id": "18515367096"} try: data = request.data.decode("utf-8") logger.info(f"新增充值明细,data{data}") data = data.replace("null", "None") data = eval(data) data = data['data'] if data['mode_type'] == "DP": res = filter_jdy_ht(data['id_card']) if not data['charge_amount']: data['charge_amount'] = 0 if not res: # 合同表单未有数据 logger.info(f"合同表单未有数据,data{data}") fsfz = data['fsfz']['dept_no'] if data['fsfz'] else "" _thread.start_new_thread(add_payment, ({"pay_amount": data['charge_amount'], "id": data['id_card'], "fs": data['fs'], "jg": data['jg'], "name": data['name'], "fsfz": fsfz, "hphm": data['hphm']}, 1)) else: logger.info(f"新增充值明细111,pay_amount: {data['charge_amount']}, id: {data['id_card']},fs: {res[1]}, jg: {res[0]}, name: {res[4]}, shfid: {res[7]},fsfz: {res[6]},hphm: {res[5]}") _thread.start_new_thread(add_payment, ({"pay_amount": data['charge_amount'], "id": data['id_card'], "fs": res[1], "jg": res[0], "name": res[4], "shfid": res[7], "fsfz": res[6], "hphm": res[5]}, 1)) return {"code": 200} else: return {"code": 200} except Exception as e: logger.info(f"addPayment,e{e},data{data}") return {} @app.route('/addlwPayment', methods=['POST']) def addlwPayment(): # 新增充值明细 {"pay_amount": 20000, "id": "18515367096"} try: data = request.data.decode("utf-8") logger.info(f"新增充值明细{data}") data = data.replace("null", "None") data = eval(data) data = data['data'] res = filter_jdy_ht(data['id_card']) if not data['price']: data['price'] = 0 if not res: # 合同表单未有数据 fsfz = data['fsfz']['dept_no'] if data['fsfz'] else "" _thread.start_new_thread(add_payment_lw, ({"pay_amount": data['price'], "id": data['id_card'], "fs": data['fs'], "jg": data['jg'], "name": data['name'], "fsfz": fsfz, "hphm": data['hphm']}, 1)) else: _thread.start_new_thread(add_payment_lw, ({"pay_amount": data['price'], "id": data['id_card'], "fs": res[1], "jg": res[0], "name": res[4], "shfid": res[7], "fsfz": res[6], "hphm": res[5]}, 1)) return {} except Exception as e: logger.info(f"addlwPayment,e{e},data{data}") return {} @app.route('/transactions', methods=['GET']) def transactions(): # 调起h5支付 try: logger.info(f"开始支付") id = request.args.get('user') price = request.args.get('price') shh = request.args.get('option') logger.info(f"===============费用缴纳类型为{shh}===============") logger.info(f"金额,{price}") if not float(price): res = filter_jdy_ht(id) _thread.start_new_thread(add_payment, ({"pay_amount": 0, "id": id, "fs": res[1], "jg": res[0], "name": res[4], "shfid": res[7], "fsfz": res[6], "hphm": res[5]}, 1)) return {} else: # 查询商户号、商户号证书 res = filter_jdy_ht(id) logger.info(f"res,{res}") if not res: return "error" logger.info(f"金额,{price}") price = float(price) * 100 if shh == '1': if not res[2] or not res[0]: return "error" fy = H5Main(res[2]) logger.info(f"发起缴纳承包金,{id}{int(time.time())}{int(price)}") message = fy.unified_order(f"{id}{int(time.time())}", int(price), "订单支付") return message else: fy = H5Main('0001000F7152364') logger.info(f"发起缴纳履约服务费{id}{int(time.time())}, {int(price)}") message = fy.unified_order(f"{id}{int(time.time())}", int(price), "订单支付") return message except Exception as e: logger.error(f"error{e}") return jsonify(error=str(e)), 500 if __name__ == '__main__': app.run(host="0.0.0.0", port=3005, processes=True)