get_order_dairly_wending_bk20201110.py 12 KB

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