order_util.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  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. logging.getLogger().setLevel(logging.WARNING)
  13. db=MysqlUtils()
  14. du=DateUtils()
  15. def get_yg_vip_channel(stage, vip_id, client_id, token):
  16. url = "https://data.yifengaf.cn:443/channeldata/data/account/list"
  17. nonce = ComUtils.get_random_str()
  18. timestamp = int(time.time())
  19. signaure = ComUtils.sha1(str(token) + str(timestamp) + str(client_id) + str(nonce))
  20. params = {
  21. "client_id": client_id,
  22. "token": token,
  23. "nonce": nonce,
  24. "timestamp": timestamp,
  25. "signaure": signaure,
  26. "vip_id": vip_id,
  27. }
  28. headers = {"Content-Type": "application/json"}
  29. r = requests.post(url=url, data=json.dumps(params), headers=headers)
  30. print(r.text)
  31. task_id = json.loads(r.text).get("data").get("task_id")
  32. db.quchen_text.execute(
  33. f"replace into yangguang_path(vip_id,task_id,stage,type) values ('{vip_id}','{task_id}','{stage}','channel')")
  34. def get_yg_data(stage,vip_id,client_id,token,start,end):
  35. url = "https://data.yifengaf.cn:443/channeldata/data/orders/list"
  36. nonce=ComUtils.get_random_str()
  37. timestamp=int(time.time())
  38. signaure =ComUtils.sha1(str(token) + str(timestamp) + str(client_id) + str(nonce))
  39. params = {
  40. "client_id": client_id,
  41. "token": token,
  42. "nonce": nonce,
  43. "timestamp": timestamp,
  44. "signaure": signaure,
  45. "vip_id": vip_id,
  46. "start_time":start, # %Y-%m-%d %H:%i:%s:
  47. "end_time":end
  48. }
  49. headers={"Content-Type":"application/json"}
  50. r=requests.post(url=url,data=json.dumps(params),headers=headers)
  51. print(r.text)
  52. task_id = json.loads(r.text).get("data").get("task_id")
  53. db.quchen_text.execute(f"replace into yangguang_path(vip_id,task_id,stage,type) values ('{vip_id}','{task_id}','{stage}','order')")
  54. def parse_yg_data(vip_id,stage):
  55. url = db.quchen_text.getOne(f"select path from yangguang_path where type='channel' and vip_id={vip_id} ")
  56. r = requests.get(url).text
  57. channel_di={}
  58. a = r.split('}')
  59. for i in a[:-1]:
  60. if i[-1] != '}':
  61. b=json.loads(i + "}", strict=False)
  62. else:
  63. b=json.loads(i, strict=False)
  64. channel_di[b["channel_id"]]=b["wx_nickname"]
  65. # print(channel_di)
  66. print(f'{stage} 有channel数:{len(channel_di)}')
  67. info=db.quchen_text.getData(f"select stage,path from yangguang_path where type='order' and vip_id={vip_id}")
  68. stage=info[0][0]
  69. path=info[0][1]
  70. text=requests.get(path).text.replace('"referral_url":,','')
  71. insert_data=[]
  72. for j in text.split("}")[:-1]:
  73. if j[-1] != '}':
  74. j=j+'}'
  75. try:
  76. di=json.loads(j, strict=False)
  77. except Exception as e:
  78. print(j)
  79. print(e)
  80. platform = "阳光"
  81. channel_id = di["channel_id"]
  82. channel=channel_di[channel_id]
  83. user_id = di["openid"]
  84. order_time = di["create_time"]
  85. reg_time = di["user_createtime"]
  86. from_novel = di["book_name"] if di['book_name'] else ''
  87. amount = di["money"]
  88. order_id = di["transaction_id"] if di["transaction_id"] else di['merchant_id']
  89. status = 2 if di['state']=="完成" else 1
  90. date = order_time[:10]
  91. insert_data.append((date,stage,platform,channel,channel_id,user_id,order_time,reg_time,amount,from_novel,order_id,status))
  92. # print(insert_data)
  93. # exit(0)
  94. print("订单数:"+ str(insert_data.__len__()))
  95. db.quchen_text.executeMany("replace into ods_order values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",tuple(insert_data))
  96. def get_hs_order_task(start, end, account):
  97. url = 'https://vip.rlcps.cn/api/getMerchants'
  98. apiKey = str(account[0])
  99. apiSecurity = account[1]
  100. timestamp = str(int(time.time()))
  101. sign = md5(apiKey + timestamp + apiSecurity).upper()
  102. params = {
  103. 'apiKey': apiKey,
  104. 'apiSecurity': apiSecurity,
  105. 'timestamp': timestamp,
  106. 'sign': sign
  107. }
  108. response_result_json = requests.post(url, params).json()
  109. if 'data' not in response_result_json.keys():
  110. print('花生账号【{apiKey}】本次请求数据异常,响应报文【{result}】'.format(apiKey=apiKey, result=response_result_json))
  111. channel_data = response_result_json['data']
  112. # print(f"{account[2]} 有channel{len(channel_data)}个:{str([i['merchant_name'] for i in channel_data])}")
  113. li = []
  114. for merchant in channel_data:
  115. orders = get_huasheng_order(start, end, account, merchant)
  116. li.extend(orders)
  117. if len(li) > 0:
  118. print(f"花生账号:{account[2]} 有order{len(li)}个")
  119. # print(li)
  120. db.quchen_text.executeMany("replace into ods_order values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",li)
  121. def get_huasheng_order(start,end, account, merchant):
  122. li =[]
  123. apiKey = str(account[0])
  124. apiSecurity = account[1]
  125. stage = account[2]
  126. timestamp = str(int(time.time()))
  127. order_url = 'https://vip.rlcps.cn/api/orderList'
  128. merchant_id = merchant['merchant_id']
  129. merchant_name = merchant['merchant_name']
  130. limit = 500
  131. for date in du.getDateLists(start,end):
  132. page = 1
  133. while True:
  134. sign = md5(apiKey + date + str(merchant_id) + timestamp + apiSecurity).upper()
  135. order_params = {
  136. 'apiKey': apiKey,
  137. 'apiSecurity': apiSecurity,
  138. 'timestamp': timestamp,
  139. 'date': date,
  140. 'merchant_id': merchant_id,
  141. 'sign': sign,
  142. 'page': page,
  143. 'limit': limit
  144. }
  145. r = requests.post(order_url, order_params)
  146. # print(r.text)
  147. response_result_json = r.json()
  148. if 'data' not in response_result_json.keys():
  149. print('花生账号【{key}】, 查询时间【{date}】, 渠道【{merchant_id}:{merchant_name}】本次请求数据异常,响应报文【{result}】'
  150. .format(key=apiKey, date=date, merchant_id=merchant_id, merchant_name=merchant_name,
  151. result=response_result_json))
  152. break
  153. if len(response_result_json['data']) == 0:
  154. break
  155. order_item_list = response_result_json['data']
  156. if len(order_item_list) == 0:
  157. break
  158. for i in order_item_list:
  159. li.append(
  160. (i['request_at'][:10],
  161. stage,
  162. '花生',
  163. merchant_name,
  164. merchant_id,
  165. i['openid'],
  166. i['request_at'],
  167. i['join_at'],
  168. i['amount'],
  169. i['book_name'],
  170. i['trans_id'] if i['trans_id'] != '' else i['order_num'],
  171. 2 if i['order_status'] == 1 else 1
  172. )
  173. )
  174. if len(order_item_list) < limit:
  175. break
  176. else:
  177. page = page + 1
  178. return li
  179. def save_hs_data(data):
  180. sql = 'replace INTO quchen_text.ods_order ' \
  181. ' VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);'
  182. db.quchen_text.executeMany(sql,data)
  183. def get_qiyue_order_task(start, end, account):
  184. """一分钟请求60次的限制"""
  185. order_list = []
  186. # 参数
  187. order_url = "https://api.zhangwenwenhua.com" + "/v1/orders"
  188. stage = account[0]
  189. token = account[1]
  190. size = 50
  191. freq=0
  192. for date in du.getDateLists(start, end):
  193. page = 1
  194. while True:
  195. timestamp = int(time.time())
  196. url = order_url + "?" + "token=" + str(token) + "&timestamp=" + str(timestamp) + "&page=" + str(
  197. page) + "&size=" + str(size) + "&date=" + date
  198. rsp=requests.get(url=url)
  199. response_result_json = rsp.json()
  200. # print(response_result_json)
  201. freq += 1
  202. if freq == 59:
  203. print("一分钟请求60次的限制 等待中")
  204. time.sleep(61)
  205. freq = 0
  206. code = response_result_json['code']
  207. if code != 0:
  208. print(stage, '七悦充值接口异常:', response_result_json)
  209. break
  210. result_data = response_result_json['data']
  211. total = result_data['total']
  212. if total <= 0:
  213. break
  214. order_item_list = result_data['data']
  215. for x in order_item_list:
  216. create_time = DateUtils.stamp_to_str(x['create_time'],'%Y-%m-%d %H:%M:%S')
  217. reg_time = DateUtils.stamp_to_str(x['user_create_time'],'%Y-%m-%d %H:%M:%S')
  218. order_list.append((
  219. create_time[:10],
  220. stage,
  221. '七悦',
  222. x['wechat_app_name'], # 公众号名称
  223. x['channel_id'],
  224. x['user_open_id'],
  225. create_time,
  226. reg_time, # 用户注册时间
  227. x['money'],
  228. x['book_name'],
  229. x['transaction_no'] if x['transaction_no'] != 0 else x['trade_no'], # 订单id
  230. x['state'])
  231. )
  232. next_page_url = result_data['next_page_url']
  233. if next_page_url is None:
  234. break
  235. page += 1
  236. # print(len(order_list))
  237. print(f'{stage} [{start}~{end}] 有订单{order_list.__len__()}')
  238. if order_list.__len__()>0:
  239. save_order(order_list)
  240. # print(order_list)
  241. def save_order(order_list):
  242. db.quchen_text.executeMany('replace into ods_order values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)',order_list)
  243. print("入库成功")
  244. def get_wd_account_siteid_list(account):
  245. url = 'https://bi.reading.163.com/dist-api/siteList'
  246. consumerkey = account[0]
  247. secretkey = account[1]
  248. stage = account[3]
  249. timestamp = int(time.time() * 1000)
  250. siteid_params = {
  251. "consumerkey": consumerkey,
  252. 'secretkey': secretkey,
  253. 'timestamp': timestamp,
  254. }
  255. sorted_data = sorted(siteid_params.items(), reverse=False)
  256. s = ""
  257. for k, v in sorted_data:
  258. s = s + str(k) + "=" + str(v)
  259. sign = md5(s).lower()
  260. siteid_params['sign'] = sign
  261. consumerkey = siteid_params['consumerkey']
  262. timestamp = siteid_params['timestamp']
  263. parameter = 'consumerkey=' + str(consumerkey) + '&timestamp=' + str(timestamp) + '&sign=' + str(sign)
  264. get_url = url + "?" + parameter
  265. while True:
  266. r = requests.get(url=get_url)
  267. if r.status_code == 200:
  268. break
  269. try:
  270. id_key_list = r.json()['data']
  271. except:
  272. return []
  273. mpid_list = []
  274. try:
  275. for id_key_val in id_key_list:
  276. mpid = dict(id_key_val)["mpId"]
  277. mpid_list.append(mpid)
  278. except Exception as e:
  279. print(stage, '站点查询返回结果:', r.json())
  280. return mpid_list
  281. def get_wending_json_object(url,params):
  282. params['timestamp'] = int(time.time()*1000)
  283. sorted_data = sorted(params.items(),reverse = False)
  284. s=""
  285. for k,v in sorted_data:
  286. s = s+str(k)+"="+str(v)
  287. sign = md5(s).lower()
  288. params['sign'] = sign
  289. consumerkey = params['consumerkey']
  290. secretkey = params['secretkey']
  291. timestamp = params['timestamp']
  292. siteid = params['siteid']
  293. pageSize = params['pageSize']
  294. starttime = params['starttime']
  295. endtime = params['endtime']
  296. page = params['page']
  297. ## +'&secretkey='+str(secretkey)
  298. parameter = 'consumerkey='+str(consumerkey)+'&timestamp='+str(timestamp)+'&siteid='+str(siteid)+'&pageSize='+str(pageSize)\
  299. +'&starttime='+str(starttime)+'&endtime='+str(endtime)+'&page='+str(page)+'&sign='+str(sign)
  300. global get_url
  301. get_url = url+"?"+parameter
  302. while True:
  303. r= requests.get(url=get_url)
  304. if r.status_code==200:
  305. break
  306. else:
  307. time.sleep(1)
  308. print("请求连接出错,等待1s...")
  309. response_result_json=r.json()
  310. del params['sign']
  311. return response_result_json
  312. def get_wd_order_task(start,end,account):
  313. order_list = []
  314. url = 'https://bi.reading.163.com/dist-api/rechargeList'
  315. consumerkey = account[0]
  316. secretkey = account[1]
  317. siteid = account[2]
  318. stage = account[3]
  319. siteid_list = get_wd_account_siteid_list(account)
  320. # print(siteid_list)
  321. if len(siteid_list) == 0:
  322. siteid_list.append(siteid)
  323. starttime = du.date_str_to_str(start)+'0000'
  324. endtime = du.date_str_to_str(end)+'2359'
  325. for siteid in siteid_list:
  326. page = 1
  327. while True:
  328. params = {
  329. 'consumerkey': consumerkey,
  330. 'secretkey': secretkey,
  331. 'timestamp': int(1601481600),
  332. 'siteid': siteid,
  333. 'pageSize': 1000,
  334. 'starttime': starttime,
  335. 'endtime': endtime,
  336. 'page': page}
  337. response_result_json = get_wending_json_object(url, params)
  338. # print(response_result_json)
  339. order_item_list = response_result_json['data']['rechargeList']
  340. for x in order_item_list:
  341. order_time = DateUtils.stamp_to_str(x['createTime'])
  342. reg_time = DateUtils.stamp_to_str(x['userRegisterTime'])
  343. order_list.append(
  344. (order_time[:10],
  345. stage,
  346. '文鼎',
  347. x['wx_mpName'],
  348. x['wx_originalId'],
  349. x['wx_user_openId'],
  350. order_time,
  351. reg_time,
  352. x['money'] / 100,
  353. x['bookTitle'] if x['bookTitle'] else '',
  354. x['ewTradeId'] if x.get('ewTradeId') else x['rechargeUuid'],
  355. 2 if x['payStatus'] == 1 else 1
  356. )
  357. )
  358. if len(order_item_list) < 1000:
  359. break
  360. else:
  361. page += 1
  362. print(f"{stage} [{start}~{end}] 有订单 {order_list.__len__()}")
  363. if order_list.__len__()>0:
  364. # print(order_list)
  365. save_order(order_list)
  366. def get_zd_order_task(start,end,account):
  367. """开始到结束最多90天"""
  368. order_list = []
  369. url = 'https://api.zhangdu520.com/channel/getorder'
  370. uid = account[0]
  371. appsecert = account[1]
  372. channel = account[2]
  373. stage = account[3]
  374. timestamp = int(time.time())
  375. sign = md5(str(uid) + '&' + appsecert + '&' + str(timestamp))
  376. for i in du.split_date2(start, end, 90):
  377. starttime = DateUtils.str_to_stamp(i[0]+' 00:00:00','%Y-%m-%d %H:%M:%S')
  378. endtime = DateUtils.str_to_stamp(i[1]+' 23:59:59','%Y-%m-%d %H:%M:%S')
  379. page = 1
  380. while True:
  381. params = {
  382. 'uid': uid,
  383. 'timestamp': timestamp,
  384. 'sign': sign,
  385. 'starttime': starttime,
  386. 'endtime': endtime,
  387. 'page': page
  388. }
  389. response_result_json = requests.get(url=url, params=params).json()
  390. # print(response_result_json)
  391. if 'data' not in response_result_json.keys():
  392. print(f'掌读账号【{uid}】, 查询时间【{i[0]} - {i[1]}】,本次请求数据异常,响应报文【{response_result_json}】')
  393. break
  394. result_data = response_result_json['data']
  395. page_count = result_data['pageCount']
  396. if page_count == 0:
  397. break
  398. order_item_list = result_data['list']
  399. for i in order_item_list:
  400. order_time = DateUtils.stamp_to_str(i['ctime'])
  401. reg_time = DateUtils.stamp_to_str(i['regtime'])
  402. order_list.append((
  403. order_time[:10],
  404. stage,
  405. '掌读',
  406. channel,
  407. uid,
  408. i['openid'],
  409. order_time,
  410. reg_time,
  411. i['amount'],
  412. i['book_entry'],
  413. i['orderno'],
  414. 2 if i['status'] == '1' else 1
  415. ))
  416. if page == page_count: # 是最后一页
  417. break
  418. page = page + 1
  419. print(f"{channel} [{start}]~[{end}] 有订单 {order_list.__len__()}")
  420. if len(order_list) > 0:
  421. # print(order_list)
  422. save_order(order_list)
  423. def get_zzy_order_task(start, end, account):
  424. url = 'https://inovel.818tu.com/partners/channel/channels/list?'
  425. key = account[0]
  426. secert = account[1]
  427. stage = account[2]
  428. sign = md5(secert + 'key=' + key)
  429. params = 'key=' + key + '&sign=' + sign
  430. response_result_json = requests.get(url + params).json() # 获取子渠道列表
  431. if 'data' not in response_result_json.keys():
  432. print('掌中云账号【{key}】本次请求数据异常,响应报文【{result}】'.format(key=key, result=response_result_json))
  433. return
  434. items = response_result_json['data']['items']
  435. print(f'VIP{account[0]} 有公众号{len(items)} ')
  436. total_order_list = []
  437. for channel in items:
  438. # 获取channel_id 后逐个拉取历史orders
  439. order_list = get_zzy_channel_order(start, end, account, channel)
  440. total_order_list.extend(order_list)
  441. print(f"{stage} [{start}]~[{end}] 有订单{total_order_list.__len__()}")
  442. if len(total_order_list) > 0:
  443. save_order(total_order_list)
  444. def get_zzy_channel_order(start, end, account, channel):
  445. get_time=DateUtils.str_to_date_str(start, f2="%Y-%m-%dT%H:%M:%S+08:00")
  446. limit_time=DateUtils.str_to_date_str(end, f2="%Y-%m-%dT%H:%M:%S+08:00")
  447. order_list = []
  448. key = account[0]
  449. secert = account[1]
  450. stage = account[2]
  451. order_url = 'https://openapi.818tu.com/partners/channel/orders/list?'
  452. channel_id = channel['id']
  453. channel_name = channel['nickname']
  454. status = str(1)
  455. page = str(1)
  456. per_page = str(1000)
  457. gte = parse.urlencode({'created_at[gte]': get_time}) # gte就是ge 大于等于开始时间
  458. lt = parse.urlencode({'created_at[lt]': limit_time}) # 小于 结束时间
  459. while True:
  460. sign = md5(secert + 'channel_id=' + str(
  461. channel_id) + '&created_at[gte]=' + get_time + '&created_at[lt]=' + limit_time + '&key=' + key + '&page=' + str(
  462. page) + '&per_page=' + per_page + '&status=' + status)
  463. params = 'channel_id=' + str(channel_id) + '&' + gte + '&' + lt + '&page=' + str(
  464. page) + '&per_page=' + per_page + '&status=' + status + '&key=' + key + '&sign=' + sign
  465. while True:
  466. r = requests.get(order_url + params)
  467. if r.status_code == 200:
  468. response_result_json = r.json()
  469. break
  470. else:
  471. time.sleep(61)
  472. print("掌中云接口调用sleep 61s...")
  473. # print(response_result_json)
  474. if 'data' not in response_result_json.keys():
  475. print(f'掌中云账号【{key}】,查询时间【{start} - {end}】,渠道【{channel_name}】本次请求数据异常,响应报文【{r.text}】')
  476. break
  477. total_count = response_result_json['data']['count'] # 总数量
  478. order_item_list = response_result_json['data']['items'] # 订单列表
  479. for i in order_item_list:
  480. order_time = DateUtils.str_to_date_str(i['created_at'], "%Y-%m-%dT%H:%M:%S+08:00", "%Y-%m-%d %H:%M:%S")
  481. 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")
  482. order_list.append((
  483. order_time[:10],
  484. stage,
  485. '掌中云',
  486. channel_name,
  487. channel_id,
  488. i['member']['openid'],
  489. order_time,
  490. reg_time,
  491. round(i['price'] / 100, 2),
  492. i['from_novel']['title'] if str(i['from_novel_id']) != 'None' else '',
  493. str(i['id']),
  494. 2 if i['status'] == 1 else 1
  495. ))
  496. if int(page) >= math.ceil(total_count / int(per_page)):
  497. break
  498. page = int(page) + 1
  499. # print(f"{channel_name}获取订单:{order_list.__len__()}")
  500. # print(order_list)
  501. return order_list
  502. if __name__ == '__main__':
  503. # account = "347347942,e0c361b54a35a55c2b6296b5a80867ce,趣程小程序"
  504. # get_hs_order_task('2021-05-01','2021-05-07',account.split(","))
  505. # print(DateUtils.stamp_to_str(1612155476,'%Y-%m-%d %H:%M:%S')[:10])
  506. # exit(0)
  507. st= et = '2021-05-07'
  508. account = "62140324,KUUxPIokqtIrtvHQ,1025010,趣程19期,qucheng19qi@163.com"
  509. get_wd_order_task(st,et,account.split(','))