OfpayHelper.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. # -*- coding: utf-8 -*-
  2. import os
  3. import re
  4. import sys
  5. import time
  6. import pymysql
  7. import logging
  8. # import jwt
  9. import json
  10. from datetime import datetime, timezone, timedelta
  11. from mitmproxy import flowfilter
  12. from mitmproxy import http
  13. from mitmproxy import ctx
  14. # from http.cookies import SimpleCookie
  15. sys.path.append('../')
  16. import utils.Utils as Utils
  17. sys.path.pop()
  18. """
  19. #http.HTTPFlow 实例 flow
  20. flow.request.http_version #HTTP 版本
  21. flow.request.headers #获取所有头信息,包含Host、User-Agent、Content-type等字段
  22. flow.request.cookies #cookie头
  23. flow.request.url #完整的请求地址,包含域名及请求参数,但是不包含放在body里面的请求参数
  24. flow.request.pretty_url #同flow.request.url目前没看出什么差别
  25. flow.request.host #域名
  26. flow.request.port #请求的目标端口
  27. flow.request.method #请求方式。POST、GET等
  28. flow.request.scheme #什么请求 ,如https
  29. flow.request.path # 请求的路径,url除域名之外的内容
  30. flow.request.get_text() #请求中body内容,有一些http会把请求参数放在body里面,那么可通过此方法获取,返回字典类型
  31. flow.request.replace() # 使用正则替换content中的内容
  32. flow.request.query #返回MultiDictView类型的数据,url直接带的键值参数
  33. flow.request.get_content()#bytes,结果如flow.request.get_text()
  34. flow.request.raw_content #bytes,结果如flow.request.get_content()
  35. flow.request.urlencoded_form #MultiDictView,content-type:application/x-www-form-urlencoded时的请求参数,不包含url直接带的键值参数
  36. flow.request.multipart_form #MultiDictView,content-type:multipart/form-data
  37. flow.request.timestamp_start #请求开始的时间戳
  38. flow.request.timestamp_end #请求结束的时间戳
  39. 时的请求参数,不包含url直接带的键值参数
  40. #以上均为获取request信息的一些常用方法,对于response,同理
  41. flow.response.status_code #状态码
  42. flow.response.headers #获取所有头信息
  43. flow.response.cookies #cookie头
  44. flow.response.text#返回内容,已解码
  45. flow.response.content #返回内容,二进制
  46. flow.response.set_text() #修改返回内容,不需要转码
  47. flow.response.replace() # 使用正则替换content中的内容
  48. flow.response.timestamp_start #响应开始的时间戳
  49. flow.response.timestamp_end #响应结束的时间戳
  50. """
  51. class OfpayHelper:
  52. order_simple_data = {
  53. "awardId": "W1155090378949787660",
  54. "activityId": "A923605206137307136",
  55. "activityName": "采集",
  56. "activityState": "2",
  57. "activityStartTime": "2022-01-01 00:00",
  58. "activityEndTime": "2888-12-31 23:59",
  59. "businessType": "4005",
  60. "outActivityCode": "eCoffee",
  61. "mobile": "",
  62. "prizeId": "sku14117",
  63. "prizeName": "数据采集成功",
  64. "prizeAlias": "",
  65. "prizeDesc": "",
  66. "prizeDescUrl": "https://mstatic.ofpay.com/marketing/upload/ca2ed3a05b2846b7909debf2df8e3495.png",
  67. "prizeBannerUrl": "https://mstatic.ofpay.com/marketing/upload/c4d1a0b94b50462eb0f040306a9badf4.png",
  68. "categoryId": "1",
  69. "rechargeType": "09",
  70. "goodsScene": "0",
  71. "goodsList": [],
  72. "orderNum": 1,
  73. "createTime": "",
  74. "imgUrl": "https://mstatic.ofpay.com/marketing/upload/fc0cc0a86db64f638d4e193913d7efea.png",
  75. "orderStatus": "3",
  76. "detailId": "T123456789",
  77. "clientAccount": "13430389115",
  78. "redeemCode": "",
  79. "redeemCodeStatus": "",
  80. "dynamicCodeSign": "1",
  81. "startEffectTime": "",
  82. "endEffectTime": "",
  83. "toExpireFlag": "0",
  84. "faceVal": "",
  85. "orderId": "T240311090006428",
  86. "tenantId": "0000000191",
  87. "price": "30",
  88. "awardPrice": "20.8",
  89. "salePrice": "20.8",
  90. "rechargeId": "R1216679598197055488",
  91. "rechargeTime": "2024-01-01 00:00:00",
  92. "payStatus": "2",
  93. "discountPrice": "",
  94. "activityPrice": "",
  95. "customerInfo": "{\"device_id\":\"D29ED082-549A-4882-98FC-8BB881D1552B\",\"loginType\":\"interactiveIGoChoose\",\"gameAccount\":\"13430389115\",\"city_code\":\"440100\",\"cisno\":\"ZbHv0CEM2cGjx0DB9DXVJg==\",\"isNewUser\":\"0\",\"marketId\":\"M923156289016692736\",\"city_name\":\"广州市\",\"phone\":\"13430389115\",\"fromEntry\":\"APP\",\"currentTimeMillis\":\"1710119786257\",\"userUuid\":\"Pfd6kjTSmjCfQ8boswe1PpAmfgZW0acz\",\"cust_id\":\"Pfd6kjTSmjCfQ8boswe1PpAmfgZW0acz\",\"invitationCode\":\"BGCKWC\"}",
  96. "callbackOrder": "",
  97. "activityRechargeEffectStartTime": "",
  98. "activityRechargeEffectEndTime": "",
  99. "accountType": "",
  100. "payFlag": "1",
  101. "activityPayFlag": True,
  102. "thirdInfo": "{\"faceValue\":\"30.00\",\"customGatewayId\":\"ZDY_ICBC_ZJWN\",\"showSign\":\"1\",\"xcxShowSign\":\"2\",\"order\":\"28\",\"toBPrice\":\"30.00\",\"showPhone\":\"1\",\"pointActivity\":\"HD0460132E7oLMG1mH\",\"stockShowSign\":\"2\"}",
  103. "vendorVoucher": "",
  104. "productUseMsg": "",
  105. "proof": "",
  106. "amount": 1,
  107. "parentActivityNo": "",
  108. "parentDetailId": "",
  109. "subOrderExt": "{\"orderStatus\":\"\",\"payStatus\":\"\"}",
  110. "logisticsNo": "",
  111. "company": "",
  112. "promoteId": "",
  113. "version": 1,
  114. "gateWayId": "",
  115. "payType": "",
  116. "needRechargeNum": "0"
  117. }
  118. def __init__(self):
  119. self.domain_name = 'market-web.ofpay.com';
  120. self.host_ip = None;
  121. ip_address = Utils.get_ip_address(self.domain_name);
  122. if ip_address:
  123. self.host_ip = ip_address;
  124. self.db_conn = None;
  125. self.connect_mysql();
  126. def connect_mysql(self):
  127. config = {
  128. 'host':'47.106.225.136',
  129. 'port':3306,
  130. 'user':'root',
  131. 'passwd':'sjojo123456',
  132. 'database':'mitmproxy',
  133. 'charset':'utf8'
  134. };
  135. db_conn = None;
  136. while True:
  137. try:
  138. db_conn = pymysql.connect(**config);
  139. db_conn.ping(reconnect=True);
  140. except pymysql.OperationalError as e:
  141. print(e);
  142. print('连接断开,正在尝试重新连接...');
  143. if db_conn:
  144. db_conn.close();
  145. db_conn = pymysql.connect(**config);
  146. time.sleep(1);
  147. else:
  148. break;
  149. self.db_conn = db_conn;
  150. def check_mysql_connect(self):
  151. try:
  152. with self.db_conn.cursor() as cursor:
  153. cursor.execute('SELECT 1');
  154. except pymysql.MySQLError as e:
  155. print(e);
  156. self.db_conn.close();
  157. print('mysql重连...');
  158. self.connect_mysql();
  159. def check_host_pass(self, host):
  160. if self.host_ip:
  161. if host != self.host_ip and host != self.domain_name:
  162. return False;
  163. else:
  164. if host != self.domain_name:
  165. return False;
  166. return True;
  167. def request(self, flow: http.HTTPFlow):
  168. if not self.check_host_pass(flow.request.host):
  169. return;
  170. url = flow.request.url;
  171. path = flow.request.path;
  172. request = flow.request;
  173. def response(self, flow: http.HTTPFlow):
  174. if not self.check_host_pass(flow.request.host):
  175. return;
  176. url = flow.request.url;
  177. path = flow.request.path;
  178. print("###[OfpayHelper]path=%s"%path);
  179. if path.startswith('/h5/union/interactiveIGoChoose/index'):
  180. self.handle_login(flow);
  181. elif path.startswith('/h5/union/api/interactiveIGoChoose/indexConfigRebuild'):
  182. self.handle_activitylist(flow);
  183. elif path.startswith('/h5/union/api/interactiveIGoChoose/orderList'):
  184. self.handle_orderlist(flow);
  185. def get_jwt_token_data(self, flow: http.HTTPFlow):
  186. request = flow.request;
  187. headers = dict(request.headers);
  188. jwt_data = None;
  189. try:
  190. jwt_str = None;
  191. if 'Authorization' in headers:
  192. jwt_str = headers['Authorization'];
  193. else:
  194. cookies = dict(request.cookies);
  195. if 'unionToken_interactiveIGoChoose' in cookies:
  196. jwt_str = cookies['unionToken_interactiveIGoChoose'];
  197. if jwt_str:
  198. jwt_data = Utils.parse_jwt(jwt_str);
  199. except jwt.PyJWTError as e:
  200. print('jwt token解析失败');
  201. else:
  202. pass
  203. finally:
  204. pass
  205. if jwt_data:
  206. payload = jwt_data['payload'];
  207. if 'customerInfo' in payload:
  208. info_str = payload['customerInfo'];
  209. customer_info = json.loads(info_str);
  210. payload['customerInfo'] = customer_info;
  211. return jwt_data;
  212. def handle_login(self, flow: http.HTTPFlow):
  213. ctx.log.info('###handle_login###');
  214. request = flow.request;
  215. response = flow.response;
  216. if not response.cookies:
  217. return;
  218. jwt_data = self.get_jwt_token_data(flow);
  219. if not jwt_data:
  220. return;
  221. payload = jwt_data['payload'];
  222. account = None;
  223. if 'customerInfo' not in payload:
  224. account = payload['customerInfo']['phone'];
  225. login_params = flow.request.query.get('loginParams');
  226. cookies = dict(request.cookies);
  227. for name, morsel in response.cookies.items():
  228. value = morsel[0];
  229. if not value:
  230. continue;
  231. cookies[name] = value;
  232. # # 获取所有的Set-Cookie头部
  233. # set_cookie_headers = flow.response.headers.get_all("Set-Cookie")
  234. # for cookie_header in set_cookie_headers:
  235. # cookie = SimpleCookie();
  236. # cookie.load(cookie_header);
  237. # # SimpleCookie对象可以像字典一样工作
  238. # for key, morsel in cookie.items():
  239. # # 这里可以添加进一步的逻辑来处理cookie的键和值
  240. # # 例如,可以检查cookie的过期时间,路径等属性
  241. # print("Attributes:", morsel);
  242. authorization = cookies['unionToken_interactiveIGoChoose'];
  243. sign_time = None;
  244. expire_time = None;
  245. try:
  246. jwt_data = Utils.parse_jwt(authorization);
  247. if not jwt_data:
  248. return;
  249. payload = jwt_data['payload'];
  250. if 'customerInfo' in payload:
  251. info_str = payload['customerInfo'];
  252. customer_info = json.loads(info_str);
  253. payload['customerInfo'] = customer_info;
  254. account = customer_info['phone'];
  255. sign_time = Utils.seconds_to_beijing_time(payload['iat']);
  256. expire_time = Utils.seconds_to_beijing_time(payload['exp']);
  257. except Exception as e:
  258. print(e);
  259. if not account:
  260. return;
  261. try:
  262. sql_query = f'''
  263. UPDATE elife_account_data
  264. SET
  265. authorization = %s,
  266. cookies = %s,
  267. update_time = %s,
  268. expire_time = %s,
  269. login_params = %s
  270. WHERE account = %s;
  271. ''';
  272. sql_params = (authorization, repr(cookies), sign_time, expire_time, login_params, account);
  273. # print(sql_params);
  274. self.check_mysql_connect();
  275. cursor = self.db_conn.cursor();
  276. cursor.execute(sql_query, sql_params);
  277. self.db_conn.commit();
  278. cursor.close();
  279. except pymysql.OperationalError as e:
  280. print(e);
  281. def handle_activitylist(self, flow: http.HTTPFlow):
  282. ctx.log.info('###handle_activitylist###');
  283. request = flow.request;
  284. response = flow.response;
  285. jwt_data = self.get_jwt_token_data(flow);
  286. if not jwt_data:
  287. return;
  288. payload = jwt_data['payload'];
  289. if 'customerInfo' not in payload:
  290. return;
  291. account = payload['customerInfo']['phone'];
  292. if not account:
  293. return;
  294. if account != '13430389115' or account != '17607571132':
  295. return;
  296. rsp_params = json.loads(response.get_text());
  297. if rsp_params['code'] != 'success':
  298. return;
  299. rsp_data = rsp_params['data'];
  300. sql_activity_query = f'''
  301. CALL UpdateElifeActivities(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);
  302. ''';
  303. sql_activity_params = [];
  304. sql_award_query = f'''
  305. CALL UpdateElifeActivityAwards(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);
  306. ''';
  307. sql_award_params = [];
  308. activity_list = rsp_params['data'];
  309. activity_sort_num = 0;
  310. for activity_info in activity_list:
  311. sql_activity_params.append(('1',
  312. activity_info['activityId'], activity_info['activityAlias'], activity_info['outActivityCode'],
  313. activity_info['activityTitle'], activity_info['activityState'], activity_info['activityIcon'],
  314. activity_info['activityLink'], activity_info['activityBanner'], activity_info['subLoginType'],
  315. activity_info['subActivityId'] if 'subActivityId' in activity_info else '', activity_info['activityDesc'], activity_sort_num));
  316. activity_sort_num += 1;
  317. award_list = activity_info['awardList'];
  318. for award_info in award_list:
  319. # print(award_info)
  320. sql_award_params.append((
  321. award_info['awardId'], award_info['prizeName'], award_info['activityId'],
  322. award_info['prizeId'], award_info['prizeDesc'], award_info['prizeBannerUrl'],
  323. award_info['prizeDescUrl'], award_info['imgUrl'], int(award_info['stockNum']),
  324. float(award_info['price']), award_info['categoryType'], award_info['goodsScene'],
  325. award_info['rechargeType'], int(award_info['useStock']), int(award_info['remainStock']),
  326. int(award_info['cycleStock']), int(award_info['cycleRemainStock']), int(award_info['orderNum']),
  327. award_info['payFlag'], award_info['thirdInfo'], award_info['awardType'],
  328. int(award_info['firstSignAward']), int(award_info['renewSignAward']), award_info['prizeAlias'] if 'prizeAlias' in award_info else '',
  329. award_info['parentAwardId'] if 'parentAwardId' in award_info else ''));
  330. try:
  331. self.check_mysql_connect();
  332. cursor = self.db_conn.cursor();
  333. cursor.executemany(sql_activity_query, sql_activity_params);
  334. cursor.executemany(sql_award_query, sql_award_params);
  335. self.db_conn.commit();
  336. cursor.close();
  337. except pymysql.OperationalError as e:
  338. print(e);
  339. def handle_orderlist(self, flow: http.HTTPFlow):
  340. ctx.log.info('###handle_orderlist###');
  341. request = flow.request;
  342. response = flow.response;
  343. cookies = dict(request.cookies); # 转换cookies格式为dict
  344. # if 'unionToken_interactiveIGoChoose' not in cookies:
  345. # return;
  346. # account = None;
  347. # try:
  348. # jwt_str = cookies['unionToken_interactiveIGoChoose'];
  349. # # payload = jwt.decode(jwt_str, '', algorithms=['HS256'], verify=False, options={'verify_signature':False});
  350. # # info_str = payload.get('customerInfo');
  351. # # 不依赖库,简单方法解析
  352. # jwt_data = Utils.parse_jwt(jwt_str);
  353. # if jwt_data:
  354. # payload = jwt_data['payload'];
  355. # info_str = payload['customerInfo'];
  356. # customer_info = json.loads(info_str);
  357. # account = customer_info['phone'];
  358. # except jwt.PyJWTError as e:
  359. # print('jwt token解析失败');
  360. # else:
  361. # pass
  362. # finally:
  363. # pass
  364. jwt_data = self.get_jwt_token_data(flow);
  365. if not jwt_data:
  366. return;
  367. payload = jwt_data['payload'];
  368. if 'customerInfo' not in payload:
  369. return;
  370. account = payload['customerInfo']['phone'];
  371. if not account:
  372. return;
  373. headers = dict(request.headers);
  374. uuid = headers['UUID'];
  375. authorization = headers['Authorization'];
  376. user_agent = headers['User-Agent'];
  377. market_id = request.query.get('marketId');
  378. event_visitor_id = request.query.get('eventVisitorId');
  379. clientAccount = account if account else '13400000000';
  380. # create_time = '2024-01-01 00:00:00';
  381. create_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S');
  382. capture_code = Utils.generate_random_code(6);
  383. simple_data = OfpayHelper.order_simple_data;
  384. simple_data['prizeDesc'] = capture_code;
  385. simple_data['createTime'] = create_time;
  386. simple_data['endEffectTime'] = create_time;
  387. # simple_data['rechargeTime'] = create_time;
  388. simple_data['clientAccount'] = clientAccount;
  389. rsp_params = json.loads(response.get_text());
  390. if rsp_params['code'] == 'success':
  391. rsp_data = rsp_params['data'];
  392. rsp_data['list'].insert(0, simple_data);
  393. update_time = create_time;
  394. sign_time = Utils.seconds_to_beijing_time(payload['iat']);
  395. expire_time = Utils.seconds_to_beijing_time(payload['exp']);
  396. simple_data['createTime'] = expire_time;
  397. simple_data['endEffectTime'] = expire_time;
  398. # simple_data['rechargeTime'] = expire_time;
  399. sql_query = f'''
  400. CALL UpdateElifeAccountData(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s);
  401. ''';
  402. sql_params = (account, uuid, authorization, repr(cookies), user_agent, market_id, event_visitor_id, capture_code , update_time, expire_time);
  403. try:
  404. self.check_mysql_connect();
  405. cursor = self.db_conn.cursor();
  406. cursor.execute(sql_query, sql_params);
  407. self.db_conn.commit();
  408. cursor.close();
  409. simple_data['prizeName'] = '数据采集成功';
  410. except pymysql.OperationalError as e:
  411. print(e);
  412. simple_data['prizeName'] = '数据采集失败';
  413. simple_data['prizeDesc'] = '';
  414. response.set_text(json.dumps(rsp_params));