order_util.py 19 KB

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