order_util.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  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. logging.getLogger().setLevel(logging.WARNING)
  12. db=MysqlUtils()
  13. du=DateUtils()
  14. def get_yg_vip_channel(stage, vip_id, client_id, token):
  15. url = "https://data.yifengaf.cn:443/channeldata/data/account/list"
  16. nonce = ComUtils.get_random_str()
  17. timestamp = int(time.time())
  18. signaure = ComUtils.sha1(str(token) + str(timestamp) + str(client_id) + str(nonce))
  19. params = {
  20. "client_id": client_id,
  21. "token": token,
  22. "nonce": nonce,
  23. "timestamp": timestamp,
  24. "signaure": signaure,
  25. "vip_id": vip_id,
  26. }
  27. headers = {"Content-Type": "application/json"}
  28. r = requests.post(url=url, data=json.dumps(params), headers=headers)
  29. print(r.text)
  30. task_id = json.loads(r.text).get("data").get("task_id")
  31. db.quchen_text.execute(
  32. f"replace into yangguang_path(vip_id,task_id,stage,type) values ('{vip_id}','{task_id}','{stage}','channel')")
  33. def get_yg_data(stage,vip_id,client_id,token,start,end):
  34. url = "https://data.yifengaf.cn:443/channeldata/data/orders/list"
  35. nonce=ComUtils.get_random_str()
  36. timestamp=int(time.time())
  37. signaure =ComUtils.sha1(str(token) + str(timestamp) + str(client_id) + str(nonce))
  38. params = {
  39. "client_id": client_id,
  40. "token": token,
  41. "nonce": nonce,
  42. "timestamp": timestamp,
  43. "signaure": signaure,
  44. "vip_id": vip_id,
  45. "start_time":start, # %Y-%m-%d %H:%i:%s:
  46. "end_time":end
  47. }
  48. headers={"Content-Type":"application/json"}
  49. r=requests.post(url=url,data=json.dumps(params),headers=headers)
  50. print(r.text)
  51. task_id = json.loads(r.text).get("data").get("task_id")
  52. db.quchen_text.execute(f"replace into yangguang_path(vip_id,task_id,stage,type) values ('{vip_id}','{task_id}','{stage}','order')")
  53. def parse_yg_data(vip_id,stage):
  54. url = db.quchen_text.getOne(f"select path from yangguang_path where type='channel' and vip_id={vip_id} ")
  55. r = requests.get(url).text
  56. channel_di={}
  57. a = r.split('}')
  58. for i in a[:-1]:
  59. if i[-1] != '}':
  60. b=json.loads(i + "}", strict=False)
  61. else:
  62. b=json.loads(i, strict=False)
  63. channel_di[b["channel_id"]]=b["wx_nickname"]
  64. # print(channel_di)
  65. print(f'{stage} 有channel数:{len(channel_di)}')
  66. info=db.quchen_text.getData(f"select stage,path from yangguang_path where type='order' and vip_id={vip_id}")
  67. stage=info[0][0]
  68. path=info[0][1]
  69. text=requests.get(path).text.replace('"referral_url":,','')
  70. insert_data=[]
  71. for j in text.split("}")[:-1]:
  72. if j[-1] != '}':
  73. j=j+'}'
  74. try:
  75. di=json.loads(j, strict=False)
  76. except Exception as e:
  77. print(j)
  78. print(e)
  79. if di["state"] == "未完成":
  80. continue
  81. platform = "阳光"
  82. channel_id = di["channel_id"]
  83. channel=channel_di[channel_id]
  84. user_id = di["openid"]
  85. order_time = di["create_time"]
  86. reg_time = di["user_createtime"]
  87. from_novel = di["book_name"]
  88. amount = di["money"]
  89. order_id = di["transaction_id"]
  90. date = DateUtils.str_to_stamp(order_time[:10])
  91. insert_data.append((date,stage,platform,channel,channel_id,user_id,order_time,reg_time,amount,from_novel,order_id))
  92. # print(insert_data)
  93. print("订单数:"+ str(insert_data.__len__()))
  94. db.quchen_text.executeMany("replace into `order`(date,stage,platform,channel,channel_id,"
  95. "user_id,order_time,reg_time,amount,from_novel,order_id) values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",tuple(insert_data))
  96. def get_hs_channel(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. return
  112. return response_result_json['data']
  113. def get_huasheng_order_task(start,end, account, merchant,li):
  114. count=0
  115. apiKey = str(account[0])
  116. apiSecurity = account[1]
  117. stage = account[2]
  118. timestamp = str(int(time.time()))
  119. order_url = 'https://vip.rlcps.cn/api/orderList'
  120. merchant_id = merchant['merchant_id']
  121. merchant_name = merchant['merchant_name']
  122. limit = 500
  123. for date in du.getDateLists(start,end):
  124. page = 1
  125. while True:
  126. sign = md5(apiKey + date + str(merchant_id) + timestamp + apiSecurity).upper()
  127. order_params = {
  128. 'apiKey': apiKey,
  129. 'apiSecurity': apiSecurity,
  130. 'timestamp': timestamp,
  131. 'date': date,
  132. 'merchant_id': merchant_id,
  133. 'sign': sign,
  134. 'page': page,
  135. 'limit': limit
  136. }
  137. r = requests.post(order_url, order_params)
  138. # print(r.text)
  139. response_result_json = r.json()
  140. if 'data' not in response_result_json.keys():
  141. print('花生账号【{key}】, 查询时间【{date}】, 渠道【{merchant_id}:{merchant_name}】本次请求数据异常,响应报文【{result}】'
  142. .format(key=apiKey, date=date, merchant_id=merchant_id, merchant_name=merchant_name,
  143. result=response_result_json))
  144. break
  145. if len(response_result_json['data']) == 0:
  146. break
  147. total_count = response_result_json['count']
  148. order_item_list = response_result_json['data']
  149. for order_item in order_item_list:
  150. if order_item['order_status'] == 1: # 1为已支付
  151. order = {}
  152. order['user_id'] = order_item['openid']
  153. order['order_id'] = order_item['trans_id']
  154. order['order_time'] = order_item['pay_at']
  155. order['reg_time'] = order_item['join_at']
  156. order['channel'] = merchant_name
  157. order['channel_id'] = merchant_id
  158. order['platform'] = '花生'
  159. order['stage'] = stage
  160. order['from_novel'] = order_item['book_name']
  161. order['amount'] = order_item['amount']
  162. order["date"]=int(time.mktime(time.strptime(order_item['pay_at'][:10],"%Y-%m-%d")))
  163. order = sorted(order.items(), key=lambda item: item[0])
  164. order = dict(order)
  165. order = tuple(order.values())
  166. if order.__len__()>0:
  167. li.append(order)
  168. count+=1
  169. if int(page) >= math.ceil(total_count / int(limit)):
  170. break
  171. page = page + 1
  172. print(f"[{merchant_name}] 订单数: {count}")
  173. def save_hs_data(data):
  174. sql = 'replace INTO quchen_text.`order` ' \
  175. '(amount,channel,channel_id,date,from_novel,order_id,order_time,platform,reg_time,stage,user_id)' \
  176. ' VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);'
  177. db.quchen_text.executeMany(sql,data)
  178. def get_qiyue_order_task(start, end, account):
  179. """一分钟请求60次的限制"""
  180. order_list = []
  181. # 参数
  182. order_url = "https://api.zhangwenwenhua.com" + "/v1/orders"
  183. stage = account[0]
  184. token = account[1]
  185. page = 1
  186. size = 50
  187. freq=0
  188. for date in du.getDateLists(start, end):
  189. while True:
  190. timestamp = int(time.time())
  191. url = order_url + "?" + "token=" + str(token) + "&timestamp=" + str(timestamp) + "&page=" + str(
  192. page) + "&size=" + str(size) + "&date=" + date
  193. response_result_json = requests.get(url=url).json()
  194. freq += 1
  195. if freq == 59:
  196. print("一分钟请求60次的限制 等待中")
  197. time.sleep(61)
  198. freq = 0
  199. code = response_result_json['code']
  200. if code != 0:
  201. print(stage, '七悦充值接口异常:', response_result_json)
  202. break
  203. result_data = response_result_json['data']
  204. total = result_data['total']
  205. if total <= 0:
  206. break
  207. order_item_list = result_data['data']
  208. for x in order_item_list:
  209. if int(x['state']) != 2:
  210. continue
  211. y = ((int(x['create_time']) + 8 * 3600) // 86400 * 86400 - 8 * 3600,
  212. stage,
  213. '七悦',
  214. x['wechat_app_name'], # 公众号名称
  215. x['channel_id'],
  216. x['user_id'],
  217. time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(x['create_time'])),
  218. time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(x['user_create_time'])), # 用户注册时间
  219. x['money'],
  220. x['book_name'],
  221. x['id'] # 订单id
  222. )
  223. order_list.append(y)
  224. next_page_url = result_data['next_page_url']
  225. if next_page_url is None:
  226. break
  227. page += 1
  228. # print(len(order_list))
  229. print(f'{stage} [{start}~{end}] 有订单{order_list.__len__()}')
  230. if order_list.__len__()>0:
  231. save_order(order_list)
  232. return order_list
  233. def save_order(order_list):
  234. db.quchen_text.executeMany('replace into `order` values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)',order_list)
  235. print("入库成功")
  236. def get_wd_account_siteid_list(account):
  237. url = 'https://bi.reading.163.com/dist-api/siteList'
  238. consumerkey = account[0]
  239. secretkey = account[1]
  240. stage = account[3]
  241. timestamp = int(time.time() * 1000)
  242. siteid_params = {
  243. "consumerkey": consumerkey,
  244. 'secretkey': secretkey,
  245. 'timestamp': timestamp,
  246. }
  247. sorted_data = sorted(siteid_params.items(), reverse=False)
  248. s = ""
  249. for k, v in sorted_data:
  250. s = s + str(k) + "=" + str(v)
  251. sign = md5(s).lower()
  252. siteid_params['sign'] = sign
  253. consumerkey = siteid_params['consumerkey']
  254. timestamp = siteid_params['timestamp']
  255. parameter = 'consumerkey=' + str(consumerkey) + '&timestamp=' + str(timestamp) + '&sign=' + str(sign)
  256. get_url = url + "?" + parameter
  257. while True:
  258. r = requests.get(url=get_url)
  259. if r.status_code == 200:
  260. break
  261. try:
  262. id_key_list = r.json()['data']
  263. except:
  264. return []
  265. mpid_list = []
  266. try:
  267. for id_key_val in id_key_list:
  268. mpid = dict(id_key_val)["mpId"]
  269. mpid_list.append(mpid)
  270. except Exception as e:
  271. print(stage, '站点查询返回结果:', r.json())
  272. return mpid_list
  273. def get_wending_json_object(url,params):
  274. params['timestamp'] = int(time.time()*1000)
  275. sorted_data = sorted(params.items(),reverse = False)
  276. s=""
  277. for k,v in sorted_data:
  278. s = s+str(k)+"="+str(v)
  279. sign = md5(s).lower()
  280. params['sign'] = sign
  281. consumerkey = params['consumerkey']
  282. secretkey = params['secretkey']
  283. timestamp = params['timestamp']
  284. siteid = params['siteid']
  285. pageSize = params['pageSize']
  286. starttime = params['starttime']
  287. endtime = params['endtime']
  288. page = params['page']
  289. paystatus = params['paystatus']
  290. ## +'&secretkey='+str(secretkey)
  291. parameter = 'consumerkey='+str(consumerkey)+'&timestamp='+str(timestamp)+'&siteid='+str(siteid)+'&pageSize='+str(pageSize)\
  292. +'&starttime='+str(starttime)+'&endtime='+str(endtime)+'&page='+str(page)+'&paystatus='+str(paystatus)+'&sign='+str(sign)
  293. global get_url
  294. get_url = url+"?"+parameter
  295. while True:
  296. r= requests.get(url=get_url)
  297. if r.status_code==200:
  298. break
  299. else:
  300. time.sleep(1)
  301. print("请求连接出错,等待1s...")
  302. response_result_json=r.json()
  303. del params['sign']
  304. return response_result_json
  305. def get_wd_order_task(start,end,account):
  306. order_list = []
  307. url = 'https://bi.reading.163.com/dist-api/rechargeList'
  308. consumerkey = account[0]
  309. secretkey = account[1]
  310. siteid = account[2]
  311. stage = account[3]
  312. siteid_list = get_wd_account_siteid_list(account)
  313. # print(siteid_list)
  314. if len(siteid_list) == 0:
  315. siteid_list.append(siteid)
  316. starttime = du.date_str_to_str(start)+'0000'
  317. endtime = du.date_str_to_str(end)+'2359'
  318. for siteid in siteid_list:
  319. page = 1
  320. while True:
  321. params = {
  322. 'consumerkey': consumerkey,
  323. 'secretkey': secretkey,
  324. 'timestamp': int(1601481600),
  325. 'siteid': siteid,
  326. 'pageSize': 1000,
  327. 'starttime': starttime,
  328. 'endtime': endtime,
  329. 'page': page,
  330. 'paystatus': 1}
  331. response_result_json = get_wending_json_object(url, params)
  332. order_item_list = response_result_json['data']['rechargeList']
  333. for x in order_item_list:
  334. createTime = time.strftime("%Y-%m-%d %H:%M:%S",
  335. time.localtime(x['createTime'] // 1000)) ## 时间戳 》struct_time 》标准时间
  336. uid_reg_time = time.strftime("%Y-%m-%d %H:%M:%S",
  337. time.localtime(x['userRegisterTime'] // 1000)) ## 13位时间戳 》标准时间
  338. y = (int(time.mktime(time.strptime(createTime[:10], '%Y-%m-%d'))),
  339. stage,
  340. '文鼎',
  341. x['wx_mpName'],
  342. x['wx_originalId'],
  343. x['userId'],
  344. createTime,
  345. uid_reg_time,
  346. x['money'] / 100,
  347. x['bookTitle'],
  348. x['ewTradeId'])
  349. order_list.append(y)
  350. if len(order_item_list) < 1000:
  351. break
  352. else:
  353. page += 1
  354. print(f"{stage} [{start}~{end}] 有订单 {order_list.__len__()}")
  355. if order_list.__len__()>0:
  356. save_order(order_list)
  357. def get_zd_order_task(start,end,account):
  358. """开始到结束最多90天"""
  359. order_list = []
  360. url = 'https://api.zhangdu520.com/channel/getorder'
  361. uid = account[0]
  362. appsecert = account[1]
  363. channel = account[2]
  364. stage = account[3]
  365. timestamp = int(time.time())
  366. sign = md5(str(uid) + '&' + appsecert + '&' + str(timestamp))
  367. for i in du.split_date2(start, end, 90):
  368. starttime = DateUtils.str_to_stamp(i[0]+' 00:00:00','%Y-%m-%d %H:%M:%S')
  369. endtime = DateUtils.str_to_stamp(i[1]+' 23:59:59','%Y-%m-%d %H:%M:%S')
  370. page = 1
  371. while True:
  372. params = {
  373. 'uid': uid,
  374. 'timestamp': timestamp,
  375. 'sign': sign,
  376. 'starttime': starttime,
  377. 'endtime': endtime,
  378. 'page': page
  379. }
  380. response_result_json = requests.get(url=url, params=params).json()
  381. if 'data' not in response_result_json.keys():
  382. print(f'掌读账号【{uid}】, 查询时间【{i[0]} - {i[1]}】,本次请求数据异常,响应报文【{response_result_json}】')
  383. break
  384. result_data = response_result_json['data']
  385. page_count = result_data['pageCount']
  386. if page_count == 0:
  387. break
  388. order_item_list = result_data['list']
  389. for order_item in order_item_list:
  390. if order_item['status'] != '1': # 1为已支付
  391. continue
  392. order_time = order_item['ctime']
  393. order = (
  394. str(DateUtils.stamp_to_date_stamp(int(order_time))),
  395. stage,
  396. '掌读',
  397. channel,
  398. uid,
  399. order_item['openid'],
  400. order_time,
  401. order_item['regtime'],
  402. order_item['amount'],
  403. order_item.get('book_entry', ''),
  404. str(order_item['orderno'])
  405. )
  406. order_list.append(order)
  407. if page == page_count: # 是最后一页
  408. break
  409. page = page + 1
  410. print(f"{channel} [{start}]~[{end}] 有订单 {order_list.__len__()}")
  411. if len(order_list) > 0:
  412. save_order(order_list)
  413. if __name__ == '__main__':
  414. get_qiyue_order_task('2021-02-01','2021-02-19',['趣程15期','eyJpdiI6ImluVWxoRUl3VTR6QU5hamlYOFBvXC9BPT0iLCJ2YWx1ZSI6Ik5IZ0N4dm5GcmJ0Zklsd0tNZ1JVSVE9PSIsIm1hYyI6IjJjODUzMjdlZTc2ODI2ZjFmY2QyYmU5MGViYTkzOGU4MDEwZTIyODIxOTE4NzgzYTNhOGQ1YWM4OGJkMDAzMmIifQ=='])