demo_baidu_ad_tk_refresh.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. # -*- codeing = utf-8 -*-
  2. # @Time : 2023/4/11 19:08
  3. # @Author : Clown
  4. # @File : demo_feiyu_ad_tk_refresh.py
  5. # @Software : PyCharm
  6. import pymysql
  7. import json
  8. import requests
  9. from datetime import datetime,timedelta
  10. def linkTomySql(host, passwd, db_name, port):
  11. '''连接至数据库返回【db】,v2新增local_infile=1 打开文件导入权限'''
  12. try:
  13. # 本地连接为:localhost 服务器连接为:124.222.188.59
  14. db = pymysql.connect (
  15. host=host, user="root",
  16. passwd=passwd,
  17. db=db_name,
  18. port=port,
  19. charset='utf8mb4',
  20. local_infile=1)
  21. print ('\nconnect to mysql server 成功')
  22. print ('---------------------------------------')
  23. except:
  24. print ("\ncould not connect to mysql server")
  25. db = "连接失败"
  26. return db
  27. # 保存tokne至数据库
  28. def save_oauth_to_db(db,rsp_data,brandName):
  29. lastCatchTime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  30. cursor = db.cursor()
  31. sql = '''INSERT INTO baidu_ad_tk_refresh VALUES (%s,%s,%s,%s);'''
  32. values = (lastCatchTime,brandName,rsp_data,0)
  33. cursor.execute(sql,values)
  34. db.commit()
  35. cursor.close()
  36. # 通过app_id查询secret
  37. def select_secret_by_app_id(db,app_id):
  38. cursor = db.cursor ()
  39. sql = f'''SELECT * FROM baidu_ad_app_id_sct WHERE app_id = '{app_id}';'''
  40. cursor.execute (sql)
  41. out = cursor.fetchall ()[0]
  42. secret =out[2]
  43. brandName = out[1]
  44. cursor.close ()
  45. return secret,brandName
  46. # 通过品牌查询app_id及对应sct
  47. def select_appId_secret_by_brandName(db,brandName):
  48. cursor = db.cursor ()
  49. sql = f'''SELECT * FROM baidu_ad_app_id_sct WHERE brandName = '{brandName}';'''
  50. cursor.execute (sql)
  51. out = cursor.fetchall ()[0]
  52. app_id = out[0]
  53. secretKey = out[2]
  54. cursor.close ()
  55. return app_id,secretKey
  56. # 通过验证码重置token
  57. def get_access_token_by_auth_code(app_id,auth_code,userId):
  58. """
  59. auth_code换取access-token详见https://ad.oceanengine.com/openapi/doc/index.html?id=1696710505596940
  60. :param auth_code:
  61. :return:
  62. """
  63. host = '124.222.188.59'
  64. passwd = '111...Clown'
  65. db_name = 'zuzu_data'
  66. port = 63306
  67. db = linkTomySql (host, passwd, db_name, port)
  68. secret,brandName = select_secret_by_app_id (db, app_id)
  69. open_api_url_prefix = "https://u.baidu.com/oauth/accessToken"
  70. url = open_api_url_prefix
  71. headers = {'Content-Type':'application/json;charset:utf-8'}
  72. data = {
  73. "appId": app_id,
  74. "secretKey": secret,
  75. "grantType": "auth_code",
  76. "authCode": auth_code,
  77. 'userId':userId
  78. }
  79. rsp = requests.post(url, json=data, headers=headers)
  80. rsp_data = rsp.text
  81. save_oauth_to_db(db,rsp_data,brandName) # 将access_token等信息进行存储
  82. db.close ()
  83. return
  84. # 查询token对应的json
  85. def selectAccessToken(db,brandName):
  86. cursor = db.cursor ()
  87. sql = f'''SELECT * FROM baidu_ad_tk_refresh WHERE brandName = '{brandName}' ORDER BY lastCatchTime DESC;'''
  88. cursor.execute (sql)
  89. out = cursor.fetchall ()[0]
  90. json_data = out[2]
  91. cursor.close ()
  92. return json_data
  93. # 刷新密钥
  94. def refreshToken(db,brandName):
  95. url = 'https://u.baidu.com/oauth/refreshToken'
  96. headers = {'Content-Type': 'application/json;charset:utf-8'}
  97. json_data = selectAccessToken(db,brandName)
  98. json_data = json.loads (json_data)['data']
  99. userId = json_data['userId']
  100. refreshToken = json_data['refreshToken']
  101. app_id, secretKey = select_appId_secret_by_brandName(db,brandName)
  102. data = {'appId':app_id,
  103. 'refreshToken':refreshToken,
  104. 'secretKey':secretKey,
  105. 'userId':userId}
  106. resp = requests.post(url,headers=headers,json=data).text
  107. save_oauth_to_db (db, resp, brandName)
  108. # 选择所有有效账户
  109. def selectAllUsers(db):
  110. cursor = db.cursor ()
  111. sql = f'''SELECT * FROM baidu_ad_app_id_sct WHERE state = 1;'''
  112. cursor.execute (sql)
  113. out = cursor.fetchall ()
  114. list_out = []
  115. for row in out:
  116. dict_out = {'brandName':row[1],
  117. 'userName':row[3]}
  118. list_out.append(dict_out)
  119. cursor.close()
  120. return list_out
  121. # 批量生成账号密钥队列
  122. def getUserListByMccid(db,brandName,userName):
  123. json_data = selectAccessToken (db,brandName)
  124. json_data = json.loads (json_data)['data']
  125. accessToken = json_data['accessToken']
  126. # print(accessToken)
  127. url = 'https://api.baidu.com/json/feed/v1/MccFeedService/getUserListByMccid'
  128. headers = {"Accept-Encoding": "gzip, deflate",
  129. "Content-Type": "application/json",
  130. "Accept": "application/json"}
  131. data = {"header": {
  132. "userName": userName,
  133. "accessToken": accessToken,
  134. "action": "API-PYTHON"},
  135. "body": {}}
  136. resp = requests.post(url,headers=headers,json=data).json()
  137. userList = resp['body']['data']
  138. list_out = []
  139. for user in userList:
  140. if user['remark'] not in ['资管','']:
  141. user_dict = {'userName':user['username'],
  142. 'accessToken':accessToken,
  143. 'brandName':user['remark'],
  144. 'routeName':'baidu'}
  145. list_out.append(user_dict)
  146. if len(list_out) == 0:
  147. list_out = [{'userName':userName,
  148. 'accessToken':accessToken,
  149. 'brandName':brandName,
  150. 'routeName':'baidu'}]
  151. return list_out
  152. # 获取所有百度投流账户信息
  153. def getAllBaiDuUsersList(db):
  154. Users = selectAllUsers (db)
  155. out_list = []
  156. for userInfo in Users:
  157. out = getUserListByMccid (db, userInfo['brandName'], userInfo['userName'])
  158. out_list = out + out_list
  159. print (out_list)
  160. return out_list
  161. # 批量更新密钥
  162. def refreshAllBaiDuUsersToken(db):
  163. Users = selectAllUsers (db)
  164. for userInfo in Users:
  165. try:
  166. refreshToken (db, userInfo['brandName'])
  167. except:
  168. print(f'【{userInfo["brandName"]}】token 更新失败 ')
  169. if __name__ == '__main__':
  170. host = 'localhost'
  171. passwd = '111...Clown'
  172. db_name = 'zuzu_data'
  173. port = 63306
  174. db = linkTomySql (host, passwd, db_name, port)
  175. getAllBaiDuUsersList(db)
  176. db.close()
  177. if 1==0:
  178. brandName = '咀咀集团'
  179. userName = '原生-hp-cxb餐01yxB23HY08201'
  180. # list_out = getUserListByMccid (brandName,userName)
  181. refreshToken (brandName)
  182. if 1==0:
  183. json_data = selectAccessToken(brandName)
  184. print (json_data)
  185. json_data = json.loads(json_data)['data']
  186. url = 'https://u.baidu.com/oauth/getUserInfo'
  187. headers = {'Content-Type': 'application/json;charset:utf-8'}
  188. data = {'openId':json_data['openId'],
  189. 'accessToken':json_data['accessToken'],
  190. 'userId':json_data['userId'],
  191. 'needSubList':True,
  192. 'lastPageMaxUcId':1,
  193. 'pageSize':500}
  194. resp = requests.post(url,headers=headers,json=data).text
  195. print(resp)