parseCreditXml.py1014 14 KB

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