order_util.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. import time
  2. from model import ComUtils
  3. import requests
  4. import json
  5. from model.DataBaseUtils import MysqlUtils
  6. from model.DateUtils import DateUtils
  7. from model.ComUtils import *
  8. import math
  9. from model.DateUtils import DateUtils
  10. import logging
  11. from urllib import parse
  12. from model.DingTalkUtils import DingTalkUtils
  13. logging.getLogger().setLevel(logging.WARNING)
  14. db=MysqlUtils()
  15. du=DateUtils()
  16. def get_hs_order_task(start, end, account):
  17. url = 'https://vip.rlcps.cn/api/getMerchants'
  18. apiKey = str(account[0])
  19. apiSecurity = account[1]
  20. timestamp = str(int(time.time()))
  21. sign = md5(apiKey + timestamp + apiSecurity).upper()
  22. params = {
  23. 'apiKey': apiKey,
  24. 'apiSecurity': apiSecurity,
  25. 'timestamp': timestamp,
  26. 'sign': sign
  27. }
  28. response_result_json = requests.post(url, params).json()
  29. if 'data' not in response_result_json.keys():
  30. print('花生账号【{apiKey}】本次请求数据异常,响应报文【{result}】'.format(apiKey=apiKey, result=response_result_json))
  31. channel_data = response_result_json['data']
  32. # print(f"{account[2]} 有channel{len(channel_data)}个:{str([i['merchant_name'] for i in channel_data])}")
  33. li = []
  34. for merchant in channel_data:
  35. orders = get_huasheng_order(start, end, account, merchant)
  36. li.extend(orders)
  37. if len(li) > 0:
  38. print(f"花生账号:{account[2]} 有order{len(li)}个")
  39. # print(li)
  40. save_order(li)
  41. def get_huasheng_order(start,end, account, merchant):
  42. li =[]
  43. apiKey = str(account[0])
  44. apiSecurity = account[1]
  45. stage = account[2]
  46. timestamp = str(int(time.time()))
  47. order_url = 'https://vip.rlcps.cn/api/orderList'
  48. merchant_id = merchant['merchant_id']
  49. merchant_name = merchant['merchant_name']
  50. limit = 500
  51. for date in du.getDateLists(start,end):
  52. page = 1
  53. while True:
  54. sign = md5(apiKey + date + str(merchant_id) + timestamp + apiSecurity).upper()
  55. order_params = {
  56. 'apiKey': apiKey,
  57. 'apiSecurity': apiSecurity,
  58. 'timestamp': timestamp,
  59. 'date': date,
  60. 'merchant_id': merchant_id,
  61. 'sign': sign,
  62. 'page': page,
  63. 'limit': limit
  64. }
  65. r = requests.post(order_url, order_params)
  66. response_result_json = r.json()
  67. if response_result_json['code']!=0:
  68. print(response_result_json)
  69. DingTalkUtils.send('花生订单接口异常'+r.text)
  70. if 'data' not in response_result_json.keys():
  71. print('花生账号【{key}】, 查询时间【{date}】, 渠道【{merchant_id}:{merchant_name}】本次请求数据异常,响应报文【{result}】'
  72. .format(key=apiKey, date=date, merchant_id=merchant_id, merchant_name=merchant_name,
  73. result=response_result_json))
  74. break
  75. if len(response_result_json['data']) == 0:
  76. break
  77. order_item_list = response_result_json['data']
  78. if len(order_item_list) == 0:
  79. break
  80. for i in order_item_list:
  81. li.append(
  82. (i['request_at'][:10],
  83. stage,
  84. '花生',
  85. merchant_name,
  86. merchant_id,
  87. i['openid'],
  88. i['request_at'],
  89. i['join_at'],
  90. i['amount'],
  91. i['book_name'],
  92. i['trans_id'] if i['trans_id'] != '' else i['order_num'],
  93. 2 if i['order_status'] == 1 else 1
  94. # i['user_id']
  95. )
  96. )
  97. if len(order_item_list) < limit:
  98. break
  99. else:
  100. page = page + 1
  101. return li
  102. def save_hs_data(data):
  103. sql = 'replace INTO quchen_text.ods_order ' \
  104. ' VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);'
  105. db.quchen_text.executeMany(sql,data)
  106. # print(order_list)
  107. def save_order(order_list):
  108. db.quchen_text.executeMany("""replace into ods_order(date,stage,platform,channel,channel_id,user_id,
  109. order_time,reg_time,amount,from_novel,order_id,status)
  110. values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)""", order_list)
  111. print("入库成功")
  112. def save_order2(order_list):
  113. db.quchen_text.executeMany("""replace into ods_order(date,stage,platform,channel,channel_id,user_id,
  114. order_time,reg_time,amount,from_novel,order_id,status,
  115. platform_user_id,wechat_app_id,book_tags,order_type,trade_no,transaction_no)
  116. values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)""", order_list)
  117. print("入库成功")
  118. def get_wd_account_siteid_list(account):
  119. url = 'https://bi.reading.163.com/dist-api/siteList'
  120. consumerkey = account[0]
  121. secretkey = account[1]
  122. stage = account[3]
  123. timestamp = int(time.time() * 1000)
  124. siteid_params = {
  125. "consumerkey": consumerkey,
  126. 'secretkey': secretkey,
  127. 'timestamp': timestamp,
  128. }
  129. sorted_data = sorted(siteid_params.items(), reverse=False)
  130. s = ""
  131. for k, v in sorted_data:
  132. s = s + str(k) + "=" + str(v)
  133. sign = md5(s).lower()
  134. siteid_params['sign'] = sign
  135. consumerkey = siteid_params['consumerkey']
  136. timestamp = siteid_params['timestamp']
  137. parameter = 'consumerkey=' + str(consumerkey) + '&timestamp=' + str(timestamp) + '&sign=' + str(sign)
  138. get_url = url + "?" + parameter
  139. while True:
  140. r = requests.get(url=get_url)
  141. if r.status_code == 200:
  142. break
  143. try:
  144. id_key_list = r.json()['data']
  145. except:
  146. return []
  147. mpid_list = []
  148. try:
  149. for id_key_val in id_key_list:
  150. mpid = dict(id_key_val)["mpId"]
  151. mpid_list.append(mpid)
  152. except Exception as e:
  153. print(stage, '站点查询返回结果:', r.json())
  154. return mpid_list
  155. def get_wending_json_object(url,params):
  156. params['timestamp'] = int(time.time()*1000)
  157. sorted_data = sorted(params.items(),reverse = False)
  158. s=""
  159. for k,v in sorted_data:
  160. s = s+str(k)+"="+str(v)
  161. sign = md5(s).lower()
  162. params['sign'] = sign
  163. consumerkey = params['consumerkey']
  164. secretkey = params['secretkey']
  165. timestamp = params['timestamp']
  166. siteid = params['siteid']
  167. pageSize = params['pageSize']
  168. starttime = params['starttime']
  169. endtime = params['endtime']
  170. page = params['page']
  171. ## +'&secretkey='+str(secretkey)
  172. parameter = 'consumerkey='+str(consumerkey)+'&timestamp='+str(timestamp)+'&siteid='+str(siteid)+'&pageSize='+str(pageSize)\
  173. +'&starttime='+str(starttime)+'&endtime='+str(endtime)+'&page='+str(page)+'&sign='+str(sign)
  174. global get_url
  175. get_url = url+"?"+parameter
  176. while True:
  177. r= requests.get(url=get_url)
  178. if r.status_code==200:
  179. break
  180. else:
  181. time.sleep(1)
  182. print("请求连接出错,等待1s...")
  183. response_result_json=r.json()
  184. del params['sign']
  185. return response_result_json
  186. def get_wd_order_task(start,end,account):
  187. order_list = []
  188. url = 'https://bi.reading.163.com/dist-api/rechargeList'
  189. consumerkey = account[0]
  190. secretkey = account[1]
  191. siteid = account[2]
  192. stage = account[3]
  193. siteid_list = get_wd_account_siteid_list(account)
  194. # print(siteid_list)
  195. if len(siteid_list) == 0:
  196. siteid_list.append(siteid)
  197. starttime = du.date_str_to_str(start)+'0000'
  198. endtime = du.date_str_to_str(end)+'2359'
  199. for siteid in siteid_list:
  200. page = 1
  201. while True:
  202. params = {
  203. 'consumerkey': consumerkey,
  204. 'secretkey': secretkey,
  205. 'timestamp': int(1601481600),
  206. 'siteid': siteid,
  207. 'pageSize': 1000,
  208. 'starttime': starttime,
  209. 'endtime': endtime,
  210. 'page': page}
  211. response_result_json = get_wending_json_object(url, params)
  212. # print(response_result_json)
  213. order_item_list = response_result_json['data']['rechargeList']
  214. for x in order_item_list:
  215. order_time = DateUtils.stamp_to_str(x['createTime'])
  216. reg_time = DateUtils.stamp_to_str(x['userRegisterTime'])
  217. order_list.append(
  218. (order_time[:10],
  219. stage,
  220. '文鼎',
  221. x['wx_mpName'],
  222. x['wx_originalId'],
  223. x['wx_user_openId'],
  224. order_time,
  225. reg_time,
  226. x['money'] / 100,
  227. x['bookTitle'] if x['bookTitle'] else '',
  228. x['ewTradeId'] if x.get('ewTradeId') else x['rechargeUuid'],
  229. 2 if x['payStatus'] == 1 else 1
  230. # ,x['userId']
  231. )
  232. )
  233. if len(order_item_list) < 1000:
  234. break
  235. else:
  236. page += 1
  237. print(f"{stage} [{start}~{end}] 有订单 {order_list.__len__()}")
  238. if order_list.__len__()>0:
  239. # print(order_list)
  240. save_order(order_list)
  241. def get_zd_order_task(start,end,account):
  242. """开始到结束最多90天"""
  243. order_list = []
  244. url = 'https://api.zhangdu520.com/channel/getorder'
  245. uid = account[0]
  246. appsecert = account[1]
  247. channel = account[2]
  248. stage = account[3]
  249. timestamp = int(time.time())
  250. sign = md5(str(uid) + '&' + appsecert + '&' + str(timestamp))
  251. for i in du.split_date2(start, end, 90):
  252. starttime = DateUtils.str_to_stamp(i[0]+' 00:00:00','%Y-%m-%d %H:%M:%S')
  253. endtime = DateUtils.str_to_stamp(i[1]+' 23:59:59','%Y-%m-%d %H:%M:%S')
  254. page = 1
  255. while True:
  256. params = {
  257. 'uid': uid,
  258. 'timestamp': timestamp,
  259. 'sign': sign,
  260. 'starttime': starttime,
  261. 'endtime': endtime,
  262. 'page': page
  263. }
  264. response_result_json = requests.get(url=url, params=params).json()
  265. # print(response_result_json)
  266. if 'data' not in response_result_json.keys():
  267. print(f'掌读账号【{uid}】, 查询时间【{i[0]} - {i[1]}】,本次请求数据异常,响应报文【{response_result_json}】')
  268. break
  269. result_data = response_result_json['data']
  270. page_count = result_data['pageCount']
  271. if page_count == 0:
  272. break
  273. order_item_list = result_data['list']
  274. for i in order_item_list:
  275. order_time = DateUtils.stamp_to_str(i['ctime'])
  276. reg_time = DateUtils.stamp_to_str(i['regtime'])
  277. order_list.append((
  278. order_time[:10],
  279. stage,
  280. '掌读',
  281. channel,
  282. uid,
  283. i['openid'],
  284. order_time,
  285. reg_time,
  286. i['amount'],
  287. i['book_entry'],
  288. i['orderno'],
  289. 2 if i['status'] == '1' else 1
  290. # ,i['userid']
  291. ))
  292. if page == page_count: # 是最后一页
  293. break
  294. page = page + 1
  295. print(f"{channel} [{start}]~[{end}] 有订单 {order_list.__len__()}")
  296. if len(order_list) > 0:
  297. # print(order_list)
  298. save_order(order_list)
  299. def get_zzy_order_task(start, end, account):
  300. url = 'https://inovel.818tu.com/partners/channel/channels/list?'
  301. key = account[0]
  302. secert = account[1]
  303. stage = account[2]
  304. sign = md5(secert + 'key=' + key)
  305. params = 'key=' + key + '&sign=' + sign
  306. response_result_json = requests.get(url + params).json() # 获取子渠道列表
  307. if 'data' not in response_result_json.keys():
  308. print('掌中云账号【{key}】本次请求数据异常,响应报文【{result}】'.format(key=key, result=response_result_json))
  309. return
  310. items = response_result_json['data']['items']
  311. print(f'VIP{account[0]} 有公众号{len(items)} ')
  312. total_order_list = []
  313. for channel in items:
  314. # 获取channel_id 后逐个拉取历史orders
  315. order_list = get_zzy_channel_order(start, end, account, channel)
  316. total_order_list.extend(order_list)
  317. print(f"{stage} [{start}]~[{end}] 有订单{total_order_list.__len__()}")
  318. if len(total_order_list) > 0:
  319. save_order(total_order_list)
  320. def get_zzy_channel_order(start, end, account, channel):
  321. get_time=DateUtils.str_to_date_str(start, f2="%Y-%m-%dT%H:%M:%S+08:00")
  322. limit_time=DateUtils.str_to_date_str(end, f2="%Y-%m-%dT%H:%M:%S+08:00")
  323. order_list = []
  324. key = account[0]
  325. secert = account[1]
  326. stage = account[2]
  327. order_url = 'https://openapi.818tu.com/partners/channel/orders/list?'
  328. channel_id = channel['id']
  329. channel_name = channel['nickname']
  330. status = str(1)
  331. page = str(1)
  332. per_page = str(1000)
  333. gte = parse.urlencode({'created_at[gte]': get_time}) # gte就是ge 大于等于开始时间
  334. lt = parse.urlencode({'created_at[lt]': limit_time}) # 小于 结束时间
  335. while True:
  336. sign = md5(secert + 'channel_id=' + str(
  337. channel_id) + '&created_at[gte]=' + get_time + '&created_at[lt]=' + limit_time + '&key=' + key + '&page=' + str(
  338. page) + '&per_page=' + per_page + '&status=' + status)
  339. params = 'channel_id=' + str(channel_id) + '&' + gte + '&' + lt + '&page=' + str(
  340. page) + '&per_page=' + per_page + '&status=' + status + '&key=' + key + '&sign=' + sign
  341. while True:
  342. r = requests.get(order_url + params)
  343. if r.status_code == 200:
  344. response_result_json = r.json()
  345. break
  346. else:
  347. time.sleep(61)
  348. print("掌中云接口调用sleep 61s...")
  349. # print(response_result_json)
  350. if 'data' not in response_result_json.keys():
  351. print(f'掌中云账号【{key}】,查询时间【{start} - {end}】,渠道【{channel_name}】本次请求数据异常,响应报文【{r.text}】')
  352. break
  353. total_count = response_result_json['data']['count'] # 总数量
  354. order_item_list = response_result_json['data']['items'] # 订单列表
  355. for i in order_item_list:
  356. order_time = DateUtils.str_to_date_str(i['created_at'], "%Y-%m-%dT%H:%M:%S+08:00", "%Y-%m-%d %H:%M:%S")
  357. reg_time = DateUtils.str_to_date_str(i['member']['created_at'], "%Y-%m-%dT%H:%M:%S+08:00", "%Y-%m-%d %H:%M:%S")
  358. order_list.append((
  359. order_time[:10],
  360. stage,
  361. '掌中云',
  362. channel_name,
  363. channel_id,
  364. i['member']['openid'],
  365. order_time,
  366. reg_time,
  367. round(i['price'] / 100, 2),
  368. i['from_novel']['title'] if str(i['from_novel_id']) != 'None' else '',
  369. str(i['id']),
  370. 2 if i['status'] == 1 else 1
  371. # ,i['id']
  372. ))
  373. if int(page) >= math.ceil(total_count / int(per_page)):
  374. break
  375. page = int(page) + 1
  376. # print(f"{channel_name}获取订单:{order_list.__len__()}")
  377. # print(order_list)
  378. return order_list
  379. def get_account(plactform, id=None):
  380. op = f" and id={id} " if id else ''
  381. data = db.quchen_text.getData(f"select text from order_account_text where platform='{plactform}' {op}")
  382. new_data = []
  383. for i in data:
  384. new_data.append(i[0].replace('\n', '').split(","))
  385. return new_data
  386. if __name__ == '__main__':
  387. # account = "347347942,e0c361b54a35a55c2b6296b5a80867ce,趣程小程序"
  388. # get_hs_order_task('2021-05-01','2021-05-07',account.split(","))
  389. # print(DateUtils.stamp_to_str(1612155476,'%Y-%m-%d %H:%M:%S')[:10])
  390. # exit(0)
  391. st= et = '2021-05-07'
  392. account = "62140324,KUUxPIokqtIrtvHQ,1025010,趣程19期,qucheng19qi@163.com"
  393. get_wd_order_task(st,et,account.split(','))