parseCreditXml.py1105 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. #coding=utf-8
  2. from xml.dom import minidom
  3. import base64
  4. import sys
  5. import os
  6. from ini_op import Config;
  7. base_dir = os.path.dirname(os.path.abspath(__file__))
  8. config = Config(base_dir+"/config.ini");
  9. productNumXy = config.get("baseconf", "productNumXy")
  10. productNumJz = config.get("baseconf","productNumJz")
  11. productNumXxw = config.get("baseconf","productNumXxw")
  12. productNumFb = config.get("baseconf", "productNumFb")
  13. productNumKcd = config.get("baseconf", "productNumKcd")
  14. productNumFd = config.get("baseconf", "productNumFd")
  15. productNumKn = config.get("baseconf", "productNumKn")
  16. productNumHst = config.get("baseconf", "productNumHst")
  17. productNum500 = config.get("baseconf", "productNum500")
  18. isPlt = config.get("baseconf", "isPlt");
  19. import xyHttp
  20. import hst_rule_set
  21. import log
  22. import shutil
  23. logger = log.logger
  24. import time
  25. from dbController import DbController
  26. dbController = DbController();
  27. import json
  28. import requests
  29. import timeit
  30. import traceback
  31. import gzip
  32. import io
  33. from xmlParser import XmlParser;
  34. from pboc.invokePboc import PBOC
  35. from mailUtil import MailUtil
  36. def gzip_str(string_):
  37. out = io.BytesIO()
  38. with gzip.GzipFile(fileobj=out, mode='w') as fo:
  39. fo.write(string_.encode())
  40. bytes_obj = out.getvalue()
  41. return bytes_obj
  42. def gunzip_bytes_obj(bytes_obj):
  43. in_ = io.BytesIO()
  44. in_.write(bytes_obj)
  45. in_.seek(0)
  46. with gzip.GzipFile(fileobj=in_, mode='rb') as fo:
  47. gunzipped_bytes_obj = fo.read()
  48. return gunzipped_bytes_obj.decode()
  49. #解析xml数据
  50. def getBusinessInfo(xmlFile):
  51. doc = minidom.parse(xmlFile)
  52. request = doc.documentElement.getElementsByTagName("request")[0]
  53. responseBody = doc.documentElement.getElementsByTagName("responseBody")[0]
  54. responseHeader = doc.documentElement.getElementsByTagName("responseHeader")[0]
  55. result = ""
  56. xmlData = ""
  57. isBaihu = "0";
  58. if len(responseBody.childNodes)==0:
  59. # mailUtil = MailUtil();
  60. # webhook = 'https://oapi.dingtalk.com/robot/send?access_token=64d8b2c7fed4949e9433b807c7c5559939f1517af8f77c1dacb4de19c6910b56'
  61. # mailUtil.dingtalk("号码:" +xmlFile.split("_")[0] + " 查询失败 ", webhook)
  62. if getNodeData(responseHeader,"resultMsg")=="查询成功,无报告":
  63. isBaihu = "1"
  64. else:
  65. isBaihu = "2"#查询失败
  66. else:
  67. responseBodyText = responseBody.childNodes[0].data
  68. decrpyt_bytes = base64.b64decode(responseBodyText)
  69. xmlData = gunzip_bytes_obj(decrpyt_bytes)
  70. # print(xmlData)
  71. xmlPath = xmlFile+".txt"
  72. with open(xmlPath, 'w', encoding='utf-8') as fp:
  73. fp.write(xmlData)
  74. # 非小赢需要解析
  75. productNum = getNodeData(request, "productNum")
  76. if productNum != productNumXy:
  77. if xmlData !="":
  78. result = parse(xmlData)
  79. data = {
  80. "businessNum":getNodeData(request,"businessNum"),
  81. "coopBusinessNum": getNodeData(request, "coopBusinessNum"),
  82. "customerNum":getNodeData(request,"customerNum"),
  83. "certificateNum": getNodeData(request, "certificateNum"),
  84. "productNum": productNum,
  85. "creditXml":xmlData,
  86. "extend": getNodeData(request, "extend"),
  87. "result":result,
  88. "isBaihu":isBaihu
  89. }
  90. return data
  91. #解析xml报文
  92. def parse(xmlData):
  93. xmlParse = XmlParser()
  94. result = ""
  95. try:
  96. result = xmlParse.parse(xmlData)
  97. except:
  98. info = sys.exc_info()
  99. logger.error(info[0])
  100. logger.error(info[1])
  101. logger.error(traceback.extract_tb(info[2], 1))
  102. return result
  103. def getNodeData(request,key):
  104. data = request.getElementsByTagName(key)[0].childNodes[0].data
  105. return data;
  106. # if __name__ == '__main__':
  107. # businessInfo = getBusinessInfo('./test.xml')
  108. # print(businessInfo)
  109. # xml = ""
  110. # data = base64.b64encode(xml.encode("UTF-8"))
  111. # print(str(data))
  112. #调用http
  113. def process(businessInfo,basePath,xml_path):
  114. productNum = businessInfo["productNum"]
  115. if productNumXy.find(productNum) >= 0:
  116. result = xyHttp.call_credit(businessInfo)
  117. # result = json.loads(result);
  118. logger.info(result)
  119. #上传审批结果
  120. jsonPath = basePath + businessInfo["certificateNum"] + ".txt"
  121. logger.info(jsonPath)
  122. with open(jsonPath, 'w', encoding='utf-8') as fp:
  123. fp.write(result)
  124. uploadJsonFile(businessInfo,jsonPath)
  125. #移动xml文件
  126. dayStrPath = basePath+productNum+"/"+time.strftime('%Y%m%d', time.localtime(time.time()))+"/";
  127. descXmlPath = dayStrPath +"xml/"+ os.path.basename(xml_path)
  128. descJsonPath = dayStrPath+"txt/" + os.path.basename(jsonPath)
  129. if not os.path.exists(basePath+productNum):
  130. os.mkdir(basePath+productNum)
  131. if not os.path.exists(dayStrPath):
  132. os.mkdir(dayStrPath)
  133. if not os.path.exists(dayStrPath+"xml/"):
  134. os.mkdir(dayStrPath + "xml/")
  135. if not os.path.exists(dayStrPath+"txt/"):
  136. os.mkdir(dayStrPath+"txt/")
  137. logger.info("移动文件 from " + xml_path + " to " + descXmlPath)
  138. if isPlt == "1":
  139. move(xml_path, descXmlPath)
  140. shutil.move(jsonPath, descJsonPath)
  141. else:
  142. #走jar包逻辑
  143. # print(businessInfo["result"])
  144. txtPath = xml_path.replace("xml","txt")
  145. with open(txtPath, 'w', encoding='utf-8') as fp:
  146. fp.write(businessInfo["result"])
  147. if productNum == productNumJz:#桔子
  148. invokePboc(businessInfo, txtPath)
  149. #移动xml文件
  150. descXmlPath = basePath + "execed_new/" + os.path.basename(xml_path)
  151. if isPlt == "1":
  152. move(xml_path, descXmlPath)
  153. elif productNum == productNumXxw:#新希望
  154. invokeXxw(businessInfo, txtPath);
  155. jsonPath = basePath + businessInfo["certificateNum"] + ".txt"
  156. #移动xml文件
  157. descXmlPath = basePath + "execed_new/" + os.path.basename(xml_path)
  158. if not os.path.exists(basePath + "execed_new/"):
  159. os.mkdir(basePath + "execed_new/")
  160. logger.info("移动文件 from " + xml_path + " to " + descXmlPath)
  161. if isPlt == "1":
  162. move(xml_path, descXmlPath)
  163. elif productNum == productNumFb or productNum== productNumKcd or productNum500.find(productNum)>=0:#没有java包 #快车道和风暴 上传500个字段
  164. logger.info(businessInfo["productNum"])
  165. uploadJsonFile(businessInfo,txtPath)
  166. # 移动xml文件
  167. descXmlPath = basePath + "execed_new/" + os.path.basename(xml_path)
  168. if not os.path.exists(basePath + "execed_new/"):
  169. os.mkdir(basePath + "execed_new/")
  170. logger.info("移动文件 from " + xml_path + " to " + descXmlPath)
  171. if isPlt == "1":
  172. move(xml_path, descXmlPath)
  173. elif productNum == productNumFd:#分蛋,上传解析后的xml
  174. uploadJsonFile(businessInfo, xml_path+".txt")
  175. # 移动xml文件
  176. descXmlPath = basePath + "execed_new/" + os.path.basename(xml_path)
  177. if not os.path.exists(basePath + "execed_new/"):
  178. os.mkdir(basePath + "execed_new/")
  179. logger.info("移动文件 from " + xml_path + " to " + descXmlPath)
  180. if isPlt == "1":
  181. move(xml_path, descXmlPath)
  182. elif productNum == productNumKn:#快牛本地jar包
  183. if businessInfo["result"]!="":
  184. result = xyHttp.callLocal(businessInfo)
  185. uploadAudit(result,businessInfo["businessNum"],productNum)
  186. else:
  187. result = {"approveResult":"0","rule":"白户"}
  188. uploadAudit(result, businessInfo["businessNum"], productNum)
  189. # 移动xml文件
  190. descXmlPath = basePath + "execed_new/" + os.path.basename(xml_path)
  191. if not os.path.exists(basePath + "execed_new/"):
  192. os.mkdir(basePath + "execed_new/")
  193. logger.info("移动文件 from " + xml_path + " to " + descXmlPath)
  194. if isPlt == "1":
  195. move(xml_path, descXmlPath)
  196. elif productNum == productNumHst:#海盛通
  197. if businessInfo["result"]!="":
  198. result = hst_rule_set.callLocal(businessInfo)
  199. uploadAudit(result,businessInfo["businessNum"],productNum)
  200. else:
  201. result = {"approveResult":"0","rule":"白户"}
  202. uploadAudit(result, businessInfo["businessNum"], productNum)
  203. # 移动xml文件
  204. descXmlPath = basePath + "execed_new/" + os.path.basename(xml_path)
  205. if not os.path.exists(basePath + "execed_new/"):
  206. os.mkdir(basePath + "execed_new/")
  207. logger.info("移动文件 from " + xml_path + " to " + descXmlPath)
  208. if isPlt == "1":
  209. move(xml_path, descXmlPath)
  210. else:
  211. i=0
  212. #本地jar
  213. if isPlt == "1":
  214. descTxtPath = basePath + "execed_txt/" + os.path.basename(txtPath)
  215. shutil.move(txtPath, descTxtPath)
  216. #调用jar包
  217. def move(xml_path, descXmlPath):
  218. try:
  219. shutil.move(xml_path, descXmlPath)
  220. shutil.move(xml_path+".txt", descXmlPath.replace("execed_new","execed_xml")+".txt")
  221. except:
  222. logger.info("移动文件 from " + xml_path + " to " + descXmlPath)
  223. def invokePboc(businessInfo,txtPath):
  224. # ===================================
  225. try:
  226. businessNum = businessInfo["businessNum"]
  227. coopBusinessNum = businessInfo["coopBusinessNum"]
  228. pboc = PBOC()
  229. jarTxt = pboc.calc(txtPath,coopBusinessNum);
  230. result = json.loads(jarTxt)
  231. logger.info(result)
  232. if result.get("errcode")== None:
  233. uploadAudit(result,businessNum,businessInfo["productNum"])
  234. else:
  235. if businessInfo["isBaihu"]=="1":
  236. result = {"approveResult":"1"}
  237. uploadAudit(result, businessNum, businessInfo["productNum"])
  238. logger.error(result["errmsg"])
  239. except:
  240. info = sys.exc_info()
  241. logger.error(info[0])
  242. logger.error(info[1])
  243. # logging.log(logging.ERROR, info[2])
  244. logger.error(traceback.extract_tb(info[2], 1))
  245. #调用xxwjar包
  246. def invokeXxw(businessInfo,txtPath):
  247. try:
  248. businessNum = businessInfo["businessNum"]
  249. coopBusinessNum = businessInfo["coopBusinessNum"]
  250. customerNum = businessInfo["customerNum"]
  251. certificateNum = businessInfo["certificateNum"]
  252. pboc = PBOC()
  253. jarTxt = pboc.calcXxw(coopBusinessNum,customerNum,txtPath);
  254. logger.info("jarTxt:"+jarTxt)
  255. result = json.loads(jarTxt)
  256. jsonPath = basePath+certificateNum+".txt"
  257. # logger.info(jsonPath)
  258. with open(jsonPath, 'w', encoding='utf-8') as fp:
  259. fp.write(jarTxt)
  260. uploadJsonFile(businessInfo,jsonPath)
  261. if not os.path.exists(basePath + "execed_txt/"):
  262. os.mkdir(basePath + "execed_txt/")
  263. descJsonPath = basePath + "execed_txt/" + os.path.basename(jsonPath)
  264. shutil.move(jsonPath, descJsonPath)
  265. except:
  266. info = sys.exc_info()
  267. logger.error(info[0])
  268. logger.error(info[1])
  269. logger.error(traceback.extract_tb(info[2], 1))
  270. #上传审批结果
  271. def uploadAudit(result,businessNum,productNum):
  272. approvalType = result["approveResult"]
  273. if productNum == productNumJz:
  274. if approvalType=="1":
  275. approvalOpinion = "征信通过"
  276. approvalType = "4"
  277. else:
  278. approvalOpinion = "征信拒绝"
  279. approvalType = "3"
  280. elif productNum == productNumKn or productNum == productNumHst:
  281. if approvalType=="1":
  282. approvalOpinion = "征信通过"
  283. approvalType = "4"
  284. else:#快牛 需要添加拒绝原因
  285. approvalOpinion = "征信拒绝" + "#" + result["rule"]
  286. approvalType = "3"
  287. taskKey = config.get("baseconf","taskKey")
  288. appoveApiUrl = config.get("baseconf","appoveApiUrl")
  289. key = config.get("baseconf", "AESKey")
  290. data = {"header":{
  291. "ticket": "2938123198320412343",
  292. "timestamp": int(int(round(time.time() * 1000+60*1000))),
  293. "nonce": config.get("baseconf", "nonce")
  294. },
  295. "body":{"approvalType": approvalType, "businessNum": businessNum,"taskKey":taskKey,"approvalOpinion":approvalOpinion}}
  296. access_token = dbController.getToken()
  297. appoveApiUrl = appoveApiUrl+"?access_token="+access_token
  298. headers = {"Content-Type": "application/json"}
  299. jsonStr = json.dumps(data);
  300. jsonStr = jsonStr.replace('"',"\\\"")#必须替换才行
  301. logger.info(jsonStr)
  302. pboc = PBOC();
  303. encryData = pboc.encrypt(jsonStr,key)
  304. encryData = encryData[0:len(encryData)-2]
  305. logger.info(encryData)
  306. response = requests.post(appoveApiUrl, data=encryData,headers=headers)
  307. text = response.text
  308. pboc = PBOC();
  309. resultText = pboc.decrypt(text, config.get("baseconf", "AESKey"))
  310. logger.info(businessNum + "#" + "uploadAudit upload_result:" + resultText)
  311. #上传解析json
  312. def uploadJsonFile(businessInfo,json_path):
  313. # ===================================
  314. try:
  315. fileName = os.path.basename(json_path)
  316. #上传文件逻辑
  317. logger.info(json_path+"#"+"准备上传文件")
  318. uploadApiUrl = config.get("baseconf", "uploadApiUrl");
  319. uploadApiUrl = uploadApiUrl + "?access_token=" + dbController.getToken()
  320. files = {'file': open(json_path, 'rb')}
  321. logger.info(fileName+"#"+"businessNum:"+businessInfo["businessNum"])
  322. data = {'docType': "23", 'businessNum': businessInfo["businessNum"]}
  323. response = requests.post(uploadApiUrl, files=files, data=data)
  324. text = response.text
  325. logger.info("上传结果:"+text)
  326. pboc = PBOC();
  327. resultText = pboc.decrypt(text,config.get("baseconf", "AESKey"))
  328. logger.info(fileName+"#"+"uploadJsonFile:" + resultText)
  329. except:
  330. info = sys.exc_info()
  331. logger.error(info[0])
  332. logger.error(info[1])
  333. # logging.log(logging.ERROR, info[2])
  334. logger.error(traceback.extract_tb(info[2], 1))
  335. if __name__ == '__main__':
  336. file_name = ""
  337. # basePath = "D:/mydocument/myproject/git/parse/"
  338. basePath = "D:/mydocument/myprojects/creditreport/parse/"
  339. file_name = "吴悦_320103198607241763_231463842247354376.xml"
  340. # file_name = "黄振武_420115199306180091_230034699446131714.xml"
  341. xml_path = basePath + file_name
  342. start = timeit.default_timer();
  343. if len(sys.argv) > 1:
  344. basePath = sys.argv[1]
  345. xml_path = basePath + sys.argv[2]
  346. file_name = sys.argv[2]
  347. logger.info(xml_path+" 解析开始")
  348. businessInfo = getBusinessInfo(xml_path)
  349. # logger.info(businessInfo)
  350. process(businessInfo,basePath,xml_path)
  351. s = timeit.default_timer() - start;
  352. logger.info(str(s) + " 秒")
  353. logger.info(xml_path+" 解析完成")