order_util.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  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(
  173. siteid) + '&pageSize=' + str(pageSize) \
  174. + '&starttime=' + str(starttime) + '&endtime=' + str(endtime) + '&page=' + str(page) + '&sign=' + str(
  175. sign)
  176. global get_url
  177. get_url = url + "?" + parameter
  178. while True:
  179. r = requests.get(url=get_url)
  180. if r.status_code == 200:
  181. break
  182. else:
  183. time.sleep(1)
  184. print("请求连接出错,等待1s...")
  185. response_result_json = r.json()
  186. del params['sign']
  187. return response_result_json
  188. def get_wd_order_task(start, end, account):
  189. order_list = []
  190. url = 'https://bi.reading.163.com/dist-api/rechargeList'
  191. consumerkey = account[0]
  192. secretkey = account[1]
  193. siteid = account[2]
  194. stage = account[3]
  195. siteid_list = get_wd_account_siteid_list(account)
  196. # print(siteid_list)
  197. if len(siteid_list) == 0:
  198. siteid_list.append(siteid)
  199. starttime = du.date_str_to_str(start) + '0000'
  200. endtime = du.date_str_to_str(end) + '2359'
  201. for siteid in siteid_list:
  202. page = 1
  203. while True:
  204. params = {
  205. 'consumerkey': consumerkey,
  206. 'secretkey': secretkey,
  207. 'timestamp': int(1601481600),
  208. 'siteid': siteid,
  209. 'pageSize': 1000,
  210. 'starttime': starttime,
  211. 'endtime': endtime,
  212. 'page': page}
  213. response_result_json = get_wending_json_object(url, params)
  214. # print(response_result_json)
  215. order_item_list = response_result_json['data']['rechargeList']
  216. for x in order_item_list:
  217. order_time = DateUtils.stamp_to_str(x['createTime'])
  218. reg_time = DateUtils.stamp_to_str(x['userRegisterTime'])
  219. order_list.append(
  220. (order_time[:10],
  221. stage,
  222. '文鼎',
  223. x['wx_mpName'],
  224. x['wx_originalId'],
  225. x['wx_user_openId'],
  226. order_time,
  227. reg_time,
  228. x['money'] / 100,
  229. x['bookTitle'] if x['bookTitle'] else '',
  230. x['ewTradeId'] if x.get('ewTradeId') else x['rechargeUuid'],
  231. 2 if x['payStatus'] == 1 else 1
  232. # ,x['userId']
  233. )
  234. )
  235. if len(order_item_list) < 1000:
  236. break
  237. else:
  238. page += 1
  239. print(f"{stage} [{start}~{end}] 有订单 {order_list.__len__()}")
  240. if order_list.__len__() > 0:
  241. # print(order_list)
  242. save_order(order_list)
  243. def get_gf_order_task(start, end, account):
  244. order_list = []
  245. url = 'https://bi.reading.163.com/dist-api/rechargeList'
  246. consumerkey = account[0]
  247. secretkey = account[1]
  248. siteid = account[2]
  249. stage = account[3]
  250. siteid_list = get_wd_account_siteid_list(account)
  251. # print(siteid_list)
  252. if len(siteid_list) == 0:
  253. siteid_list.append(siteid)
  254. starttime = du.date_str_to_str(start) + '0000'
  255. endtime = du.date_str_to_str(end) + '2359'
  256. for siteid in siteid_list:
  257. page = 1
  258. while True:
  259. params = {
  260. 'consumerkey': consumerkey,
  261. 'secretkey': secretkey,
  262. 'timestamp': int(1601481600),
  263. 'siteid': siteid,
  264. 'pageSize': 1000,
  265. 'starttime': starttime,
  266. 'endtime': endtime,
  267. 'page': page}
  268. response_result_json = get_wending_json_object(url, params)
  269. # print(response_result_json)
  270. print(response_result_json)
  271. order_item_list = response_result_json['data']['rechargeList']
  272. print(order_item_list)
  273. for x in order_item_list:
  274. order_time = DateUtils.stamp_to_str(x['createTime'])
  275. reg_time = DateUtils.stamp_to_str(x['userRegisterTime'])
  276. order_list.append(
  277. (order_time[:10],
  278. stage,
  279. '国风',
  280. x['wx_mpName'],
  281. x['wx_originalId'],
  282. x['wx_user_openId'],
  283. order_time,
  284. reg_time,
  285. x['money'] / 100,
  286. x['bookTitle'] if x['bookTitle'] else '',
  287. x['ewTradeId'] if x.get('ewTradeId') else x['rechargeUuid'],
  288. 2 if x['payStatus'] == 1 else 1
  289. # ,x['userId']
  290. )
  291. )
  292. if len(order_item_list) < 1000:
  293. break
  294. else:
  295. page += 1
  296. print(f"{stage} [{start}~{end}] 有订单 {order_list.__len__()}")
  297. if order_list.__len__() > 0:
  298. print(order_list)
  299. sum = 0
  300. for _ in order_list:
  301. sum = sum + _[8]
  302. print(sum)
  303. save_order(order_list)
  304. def get_zd_order_task(start, end, account):
  305. """开始到结束最多90天"""
  306. order_list = []
  307. url = 'https://api.zhangdu520.com/channel/getorder'
  308. uid = account[0]
  309. appsecert = account[1]
  310. channel = account[2]
  311. stage = account[3]
  312. timestamp = int(time.time())
  313. sign = md5(str(uid) + '&' + appsecert + '&' + str(timestamp))
  314. for i in du.split_date2(start, end, 90):
  315. starttime = DateUtils.str_to_stamp(i[0] + ' 00:00:00', '%Y-%m-%d %H:%M:%S')
  316. endtime = DateUtils.str_to_stamp(i[1] + ' 23:59:59', '%Y-%m-%d %H:%M:%S')
  317. page = 1
  318. while True:
  319. params = {
  320. 'uid': uid,
  321. 'timestamp': timestamp,
  322. 'sign': sign,
  323. 'starttime': starttime,
  324. 'endtime': endtime,
  325. 'page': page
  326. }
  327. response_result_json = requests.get(url=url, params=params).json()
  328. # print(response_result_json)
  329. if 'data' not in response_result_json.keys():
  330. print(f'掌读账号【{uid}】, 查询时间【{i[0]} - {i[1]}】,本次请求数据异常,响应报文【{response_result_json}】')
  331. break
  332. result_data = response_result_json['data']
  333. page_count = result_data['pageCount']
  334. if page_count == 0:
  335. break
  336. order_item_list = result_data['list']
  337. for i in order_item_list:
  338. order_time = DateUtils.stamp_to_str(i['ctime'])
  339. reg_time = DateUtils.stamp_to_str(i['regtime'])
  340. order_list.append((
  341. order_time[:10],
  342. stage,
  343. '掌读',
  344. channel,
  345. uid,
  346. i['openid'],
  347. order_time,
  348. reg_time,
  349. i['amount'],
  350. i['book_entry'],
  351. i['orderno'],
  352. 2 if i['status'] == '1' else 1
  353. # ,i['userid']
  354. ))
  355. if page == page_count: # 是最后一页
  356. break
  357. page = page + 1
  358. print(f"{channel} [{start}]~[{end}] 有订单 {order_list.__len__()}")
  359. if len(order_list) > 0:
  360. # print(order_list)
  361. save_order(order_list)
  362. def get_zzy_order_task(start, end, account):
  363. url = 'https://inovel.818tu.com/partners/channel/channels/list?'
  364. key = account[0]
  365. secert = account[1]
  366. stage = account[2]
  367. sign = md5(secert + 'key=' + key)
  368. params = 'key=' + key + '&sign=' + sign
  369. response_result_json = requests.get(url + params).json() # 获取子渠道列表
  370. if 'data' not in response_result_json.keys():
  371. print('掌中云账号【{key}】本次请求数据异常,响应报文【{result}】'.format(key=key, result=response_result_json))
  372. return
  373. items = response_result_json['data']['items']
  374. print(f'VIP{account[0]} 有公众号{len(items)} ')
  375. total_order_list = []
  376. for channel in items:
  377. # 获取channel_id 后逐个拉取历史orders
  378. order_list = get_zzy_channel_order(start, end, account, channel)
  379. total_order_list.extend(order_list)
  380. print(f"{stage} [{start}]~[{end}] 有订单{total_order_list.__len__()}")
  381. if len(total_order_list) > 0:
  382. save_order(total_order_list)
  383. def get_zzy_channel_order(start, end, account, channel):
  384. get_time = DateUtils.str_to_date_str(start, f2="%Y-%m-%dT%H:%M:%S+08:00")
  385. limit_time = DateUtils.str_to_date_str(end, f2="%Y-%m-%dT%H:%M:%S+08:00")
  386. order_list = []
  387. key = account[0]
  388. secert = account[1]
  389. stage = account[2]
  390. order_url = 'https://openapi.818tu.com/partners/channel/orders/list?'
  391. channel_id = channel['id']
  392. channel_name = channel['nickname']
  393. status = str(1)
  394. page = str(1)
  395. per_page = str(1000)
  396. gte = parse.urlencode({'created_at[gte]': get_time}) # gte就是ge 大于等于开始时间
  397. lt = parse.urlencode({'created_at[lt]': limit_time}) # 小于 结束时间
  398. while True:
  399. sign = md5(secert + 'channel_id=' + str(
  400. channel_id) + '&created_at[gte]=' + get_time + '&created_at[lt]=' + limit_time + '&key=' + key + '&page=' + str(
  401. page) + '&per_page=' + per_page + '&status=' + status)
  402. params = 'channel_id=' + str(channel_id) + '&' + gte + '&' + lt + '&page=' + str(
  403. page) + '&per_page=' + per_page + '&status=' + status + '&key=' + key + '&sign=' + sign
  404. while True:
  405. r = requests.get(order_url + params)
  406. if r.status_code == 200:
  407. response_result_json = r.json()
  408. break
  409. else:
  410. time.sleep(61)
  411. print("掌中云接口调用sleep 61s...")
  412. # print(response_result_json)
  413. if 'data' not in response_result_json.keys():
  414. print(f'掌中云账号【{key}】,查询时间【{start} - {end}】,渠道【{channel_name}】本次请求数据异常,响应报文【{r.text}】')
  415. break
  416. total_count = response_result_json['data']['count'] # 总数量
  417. order_item_list = response_result_json['data']['items'] # 订单列表
  418. for i in order_item_list:
  419. order_time = DateUtils.str_to_date_str(i['created_at'], "%Y-%m-%dT%H:%M:%S+08:00", "%Y-%m-%d %H:%M:%S")
  420. reg_time = DateUtils.str_to_date_str(i['member']['created_at'], "%Y-%m-%dT%H:%M:%S+08:00",
  421. "%Y-%m-%d %H:%M:%S")
  422. order_list.append((
  423. order_time[:10],
  424. stage,
  425. '掌中云',
  426. channel_name,
  427. channel_id,
  428. i['member']['openid'],
  429. order_time,
  430. reg_time,
  431. round(i['price'] / 100, 2),
  432. i['from_novel']['title'] if str(i['from_novel_id']) != 'None' else '',
  433. str(i['id']),
  434. 2 if i['status'] == 1 else 1
  435. # ,i['id']
  436. ))
  437. if int(page) >= math.ceil(total_count / int(per_page)):
  438. break
  439. page = int(page) + 1
  440. # print(f"{channel_name}获取订单:{order_list.__len__()}")
  441. # print(order_list)
  442. return order_list
  443. def get_account(plactform, id=None):
  444. op = f" and id={id} " if id else ''
  445. data = db.quchen_text.getData(f"select text from order_account_text where platform='{plactform}' {op}")
  446. new_data = []
  447. for i in data:
  448. new_data.append(i[0].replace('\n', '').split(","))
  449. return new_data
  450. if __name__ == '__main__':
  451. # account = "347347942,e0c361b54a35a55c2b6296b5a80867ce,趣程小程序"
  452. # get_hs_order_task('2021-05-01','2021-05-07',account.split(","))
  453. # print(DateUtils.stamp_to_str(1612155476,'%Y-%m-%d %H:%M:%S')[:10])
  454. # exit(0)
  455. st = et = '2021-05-07'
  456. account = "62140324,KUUxPIokqtIrtvHQ,1025010,趣程19期,qucheng19qi@163.com"
  457. get_wd_order_task(st, et, account.split(','))