get_order_dairly_wending.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # 20201104
  4. ## 20201106新添加 文鼎 平台接口
  5. ########################## 文鼎订单接口,返回数据格式
  6. '''
  7. {
  8. "code": 200,
  9. "data": {
  10. "totalPage": 1,
  11. "rechargeList": [
  12. {
  13. "userId": 1067,
  14. "nickName": "海洁测试!",
  15. "userFollowTime": 1512717067449,
  16. "wx_originalId": "gh_3f1fc031329d",
  17. "wx_mpName": "测试公众号",
  18. "wx_user_openId": "odjo61rGnt6Sgl6CeWhPZTfve7eA",
  19. "rechargeUuid": "1fd47b51-1256-43ce-a72d-3266e23235ba",
  20. "rechargeMethod": 1,
  21. "money": 100,
  22. "createTime": 1512717069449,
  23. "payStatus": 0
  24. },
  25. ]
  26. '''
  27. ##########################
  28. import hashlib
  29. import time
  30. import datetime
  31. from concurrent.futures import ProcessPoolExecutor
  32. import requests
  33. from util import date_util
  34. from util import platform_config_util ## 账号配置
  35. from util import robust_util
  36. from apscheduler.schedulers.blocking import BlockingScheduler
  37. from util.MySQLConnection import MySQLConnection
  38. #import random
  39. #import math
  40. #from urllib import parse
  41. def md5(s):
  42. md5 = hashlib.md5()
  43. md5.update(s.encode("utf-8"))
  44. return md5.hexdigest()
  45. def getSelfDateStr(times=time.time(),date_format='%Y%m%d'):
  46. """
  47. ## 20201028添加,阳光接口,文鼎接口,日期参数请求格式20201028,一日一拉api数据
  48. description: 获取指定时间戳
  49. time: 秒 默认当前时间
  50. return: 返回指定时间戳的前一日日期 。 比如 :接收20190512号的时间戳,返回 20190513 -> str
  51. tips: 一天86400秒
  52. """
  53. timestamps = str(time.strftime(date_format,time.localtime(times)))
  54. return timestamps
  55. def get_wending_account_list():
  56. """
  57. des cription: 文鼎账号列表
  58. return: [['consumerkey', 'secretkey', 'siteid', 'stage', 'account']] ->list
  59. """
  60. return platform_config_util.get_account_list('文鼎', 'wending_account_config.csv')
  61. ## 5线程并发
  62. @robust_util.catch_exception
  63. def get_wending_order(st,et,account_list):
  64. total_order_list = ()
  65. start_exec_seconds = date_util.getCurrentSecondTime()
  66. #account_list = get_wending_account_list()
  67. executor = ProcessPoolExecutor(max_workers=5)
  68. futures = []
  69. for account in account_list:
  70. future = executor.submit(get_wending_order_task, st, et, account)
  71. futures.append(future)
  72. executor.shutdown(True)
  73. for future in futures:
  74. order_list = future.result()
  75. if len(order_list) > 0:
  76. total_order_list = order_list + total_order_list
  77. print('文鼎订单数量:', len(total_order_list), '执行时长(秒):', date_util.getCurrentSecondTime() - start_exec_seconds)
  78. return total_order_list
  79. ## 获取文鼎账号的站点list
  80. def get_wd_account_siteid_list(account):
  81. url = 'https://bi.reading.163.com/dist-api/siteList'
  82. consumerkey = account[0]
  83. secretkey = account[1]
  84. stage = account[3]
  85. timestamp = int(time.time()*1000)
  86. judge = True
  87. while judge:
  88. siteid_params = {
  89. "consumerkey":consumerkey,
  90. 'secretkey':secretkey,
  91. 'timestamp':timestamp,
  92. }
  93. sorted_data = sorted(siteid_params.items(),reverse = False)
  94. s=""
  95. for k,v in sorted_data:
  96. s = s+str(k)+"="+str(v)
  97. sign = md5(s).lower()
  98. siteid_params['sign'] = sign
  99. consumerkey = siteid_params['consumerkey']
  100. timestamp = siteid_params['timestamp']
  101. #secretkey = siteid_params['secretkey']
  102. parameter = 'consumerkey='+str(consumerkey)+'&timestamp='+str(timestamp)+'&sign='+str(sign)
  103. get_url = url+"?"+parameter
  104. response_result_json = requests.get(url=get_url).json()
  105. '''
  106. 站点json返回格式如下
  107. {'code': 200, 'data': [
  108. {'mpId': 1023064, 'mpName': '流云书楼', 'siteList': [{'id': 1023064, 'domain': 'lysl1.reading.163.com', 'name': '流云书楼', 'fileKey': 'Pld5F38EmbmeD1pV'}]},
  109. {'mpId': 1025058, 'mpName': '骁骑文选', 'siteList': [{'id': 1025058, 'domain': 'xqwx.reading.163.com', 'name': '骁骑文选', 'fileKey': 'ODUXIVk3Y5vKM59d'}]}
  110. ], 'message': 'success'}
  111. '''
  112. code = response_result_json['code']
  113. if code != 200:
  114. print( stage,'文鼎siteid站点接口异常:',response_result_json,'传入参数', siteid_params,"请求url",get_url)
  115. break
  116. #print('返回结果:',response_result_json)
  117. id_key_list = response_result_json['data']
  118. mpid_list = []
  119. try:
  120. for id_key_val in id_key_list:
  121. mpid = dict(id_key_val)["mpId"]
  122. mpid_list.append(mpid)
  123. except Exception as e:
  124. print(stage,'站点查询返回结果:',response_result_json)
  125. judge = False
  126. print(stage,'文鼎siteid列表:',mpid_list)
  127. return mpid_list
  128. ## 根据url,传入params获取json对象
  129. def get_wending_json_object(url,params):
  130. params['timestamp'] = int(time.time()*1000)
  131. sorted_data = sorted(params.items(),reverse = False)
  132. s=""
  133. for k,v in sorted_data:
  134. s = s+str(k)+"="+str(v)
  135. sign = md5(s).lower()
  136. params['sign'] = sign
  137. consumerkey = params['consumerkey']
  138. secretkey = params['secretkey']
  139. timestamp = params['timestamp']
  140. siteid = params['siteid']
  141. pageSize = params['pageSize']
  142. starttime = params['starttime']
  143. endtime = params['endtime']
  144. page = params['page']
  145. paystatus = params['paystatus']
  146. ## +'&secretkey='+str(secretkey)
  147. parameter = 'consumerkey='+str(consumerkey)+'&timestamp='+str(timestamp)+'&siteid='+str(siteid)+'&pageSize='+str(pageSize)\
  148. +'&starttime='+str(starttime)+'&endtime='+str(endtime)+'&page='+str(page)+'&paystatus='+str(paystatus)+'&sign='+str(sign)
  149. global get_url
  150. get_url = url+"?"+parameter
  151. response_result_json = requests.get(url=get_url).json()
  152. #response_result_json = requests.get(url=url, params=params).json()
  153. del params['sign']
  154. return response_result_json
  155. ## 具体文鼎任务
  156. def get_wending_order_task(st,et,account):
  157. order_list = ()
  158. url = 'https://bi.reading.163.com/dist-api/rechargeList'
  159. ## 接口鉴权参数
  160. consumerkey = account[0]
  161. secretkey = account[1]
  162. ## 订单参数
  163. siteid = account[2]
  164. pageSize = 1000
  165. page = 1
  166. paystatus = 1
  167. ## 需要保存到订单的标签期数
  168. stage = account[3]
  169. jud = True
  170. while jud:
  171. if st >= et:
  172. break
  173. starttime = getSelfDateStr(st,'%Y%m%d%H%M')
  174. endtime = getSelfDateStr(et,'%Y%m%d%H%M')
  175. siteid_list = get_wd_account_siteid_list(account)
  176. if len(siteid_list) == 0:
  177. break
  178. for siteid in siteid_list:
  179. params = {
  180. 'consumerkey': consumerkey,
  181. 'secretkey':secretkey,
  182. 'timestamp':int(1601481600),
  183. 'siteid':siteid,
  184. 'pageSize':pageSize,
  185. 'starttime':starttime,
  186. 'endtime':endtime,
  187. 'page':page,
  188. 'paystatus':paystatus
  189. }
  190. response_result_json = get_wending_json_object(url,params)
  191. code = response_result_json['code']
  192. if code != 200:
  193. print('文鼎查询充值接口异常:',response_result_json,'传入参数', params,"请求url",get_url)
  194. break
  195. totalPag = response_result_json['data']['totalPage']
  196. if totalPag <= 0:
  197. break
  198. for page in range(1,totalPag+1):
  199. params['page'] = page
  200. response_result_json = get_wending_json_object(url,params)
  201. order_item_list = response_result_json['data']['rechargeList']
  202. '''
  203. print(order_item_list)
  204. [{
  205. 'userId': 48267585, 'userRegisterTime': 1568671618894, 'nickName': '\ue04a邓泽群\ue04a爱花园', 'ip': '124.13.64.179'
  206. , 'userAgent': 'Mozilla/5.0 (Linux; Android 9; /arm64'
  207. , 'userFollowTime': 1568671618894, 'wx_originalId': 'gh_0beeff4c0d70', 'wx_mpName': '美语阅读', 'wx_user_openId': 'oWL046E86PdO9wX34naL6IIwfaVc'
  208. , 'rechargeUuid': '38fc210f-8e7d-4ae5-a395-d33c2a80e234', 'sourceUuid': 'ts_b4651ee782e94cce8fc6def301de1367_4', 'bookTitle': '绝代医相'
  209. , 'ewTradeId': '4200000687202010012870758048', 'payTime': 1601565287000, 'rechargeMethod': 1, 'money': 2900, 'createTime': 1601565278043
  210. , 'updateTime': 1601565288057, 'payStatus': 1
  211. }]
  212. '''
  213. ## 获取该页数据
  214. for x in order_item_list:
  215. y={}
  216. y['date'] = (int(x['payTime']//1000)+ 8 * 3600) // 86400 * 86400 - 8 * 3600 ## 网易的是13位时间戳
  217. y['platform'] = '文鼎'
  218. y['channel'] = x['wx_mpName'] ## 公众号名称
  219. y['channel_id'] = x['wx_originalId'] ## 公众号id
  220. y['from_novel'] = x['bookTitle'] ## 小说名称
  221. y['user_id'] = x['userId'] ## 付费用户uid
  222. y['stage'] = stage ## 期数
  223. createTime = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(x['createTime']//1000)) ## 时间戳 》struct_time 》标准时间
  224. y['order_time']= createTime ## 订单生成时间
  225. y['amount']=x['money']/100 ## 原数据单位:分
  226. uid_reg_time = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(x['userRegisterTime']//1000)) ## 13位时间戳 》标准时间
  227. y['reg_time']= uid_reg_time ## 用户注册时间
  228. y['order_id']= x['ewTradeId'] ## 订单id
  229. y = sorted(y.items(), key=lambda item:item[0])
  230. y = dict(y)
  231. y = tuple(y.values())
  232. order_list = order_list+((y),)
  233. if totalPag==params['page']:
  234. break
  235. jud = False
  236. print(f"文鼎数据日期-{starttime}到{endtime}-期数-{stage}-获取数据-{len(order_list)}条,例如》{order_list[0:1]}")
  237. return order_list
  238. def batch_save_order(data):
  239. if data is None or len(data) == 0:
  240. print('数据为空,不执行数据库操作!')
  241. else:
  242. sql = 'INSERT IGNORE INTO quchen_text.order(amount,channel,channel_id,date,from_novel,order_id,order_time,platform,reg_time,stage,user_id) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);'
  243. connect = MySQLConnection()
  244. try:
  245. num = connect.batch(sql, data)
  246. # 提交
  247. connect.commit()
  248. print('订单数据最终入库【{num}】条'.format(num=num))
  249. except Exception as e:
  250. print('订单数据入库失败:', e)
  251. finally:
  252. connect.close()
  253. def start_order_job():
  254. start_exec_seconds = date_util.getCurrentSecondTime()
  255. #st_unix, et_unix = date_util.getPreviousHourAndCurrentHourSecondTime(start_exec_seconds)
  256. # st_unix = 1602313200 # 2020/10/10 15:0:0
  257. # et_unix = 1602316800 # 2020/10/10 16:0:0
  258. #print('查询开始时间:', st_unix, date_util.getSecondsToDatetime(st_unix))
  259. #print('查询结束时间:', et_unix, date_util.getSecondsToDatetime(et_unix))
  260. ## 20201105添加文鼎平台
  261. st_unix = date_util.getYesterdayStartTime()
  262. et_unix = date_util.getTodayStartTime()
  263. account_list = get_wending_account_list()
  264. '''
  265. ## 2个账户测试看看
  266. account_list = [
  267. ['68442881','RFygHhX16LEYYe8i','1014108','趣程20期','qucheng20qi@163.com'],
  268. ['77257999','86nPtJdYLe1k81gE','1021116','趣程21期','qucheng21qi@163.com']
  269. ]
  270. '''
  271. batch_save_order(get_wending_order(st_unix, et_unix,account_list))
  272. print('订单同步执行时间(秒):', date_util.getCurrentSecondTime() - start_exec_seconds)
  273. start_job_time = '2020-11-11 02:00:00'
  274. if __name__ == '__main__':
  275. scheduler = BlockingScheduler()
  276. scheduler.add_job(start_order_job, 'interval', days =1 ,start_date=start_job_time)
  277. #scheduler.add_job(start_order_job, 'interval',days =1,hours = 2,minutes = 0,seconds = 0)
  278. #线上是24h执行一次
  279. scheduler.start()
  280. '''
  281. if __name__ == '__main__':
  282. start_order_job()
  283. account_list = [
  284. ['11790115','VjVIGRX5YgJCGQjC','1023064','趣程15期','qucheng15qi@163.com'],
  285. ['50465587','E5D1qzGtmhbx5EAS','1025020','趣程24期','qucheng24qi@163.com'],
  286. ['77257999','86nPtJdYLe1k81gE','1021116','趣程21期','qucheng21qi@163.com']
  287. ]
  288. '''