order_util.py 19 KB

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