access_token.py 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import os
  2. import sys
  3. sys.path.append(os.path.dirname(os.path.dirname(__file__)))
  4. import httpx
  5. from config import logger
  6. from typing import Optional
  7. from pydantic import BaseModel
  8. class DouyinAccessTokenResponse(BaseModel):
  9. error_code: int
  10. data: dict
  11. message: str
  12. async def check_access_token_response(response_json: dict):
  13. model_data = DouyinAccessTokenResponse(**response_json)
  14. if model_data.error_code != 0:
  15. raise Exception(f"获取 access token 失败,错误码:{model_data.error_code}")
  16. return model_data.data
  17. async def get_access_token(code):
  18. client_key = os.environ.get("CLIENT_KEY") # 从环境变量中获取 client_key
  19. client_secret = os.environ.get("CLIENT_SECRET") # 从环境变量中获取 client_secret
  20. async with httpx.AsyncClient() as client:
  21. response = await client.post(
  22. "https://open.douyin.com/oauth/access_token/",
  23. headers={"Content-Type": "application/json"},
  24. json={
  25. "grant_type": "authorization_code",
  26. "client_key": client_key,
  27. "client_secret": client_secret,
  28. "code": code,
  29. },
  30. )
  31. ''' response success:
  32. {
  33. "data": {
  34. "access_token": "act.f7094fbffab2ecbfc45e9af9c32bc241oYdckvBKe82BPx8T******",
  35. "captcha": "",
  36. "desc_url": "",
  37. "description": "",
  38. "error_code": 0,
  39. "expires_in": 1296000,
  40. "log_id": "20230525105733ED3ED7AC56A******",
  41. "open_id": "b9b71865-7fea-44cc-******",
  42. "refresh_expires_in": 2592000,
  43. "refresh_token": "rft.713900b74edde9f30ec4e246b706da30t******",
  44. "scope": "user_info"
  45. },
  46. "message": "success"
  47. }
  48. response error:
  49. {
  50. "data": {
  51. "description": "Parameter error",
  52. "error_code": 2100005
  53. },
  54. "extra": {
  55. "logid": "2020070614111601022506808001045D59",
  56. "now": 1594015876138
  57. }
  58. }
  59. '''
  60. logger.debug(response.json())
  61. return response.json().get("data")
  62. # 单元测试
  63. def main():
  64. # 访问: https://swl-8l9.pages.dev/ 点击立即体验
  65. # 浏览器打开调试模式F12,扫码登录
  66. # 在浏览器调试窗口 - 网络 - 名称 - 第一条 /verify?code=936c3671e073703c25Ze7zlgwxcOjvsYJ6Iz&state=&scope - 获得 code
  67. import asyncio
  68. res = asyncio.run(get_access_token("936c3671e073703c25Ze7zlgwxcOjvsYJ6Iz"))
  69. print("res:",res)
  70. '''
  71. {'access_token': 'act.3.wl8L3DFQ3sj3uKYzQShOSs8HbOgKh0FVvjxKeaTum0ZOEXoyBI8D1N7gTBqGbrY32KP-Pm41EAvcobSheOBi8tvRdhj7m5-5ZVoprZZu_GN5J2KnH2fZ_X9_l7Q6iFyvpPoMkX3Zyom3PCkeRZp4Jg9sE2ZiwuvZVdnvft0A25uBWXvj2IEbWW_0Bf8=', 'captcha': '', 'desc_url': '', 'description': '', 'error_code': 0, 'expires_in': 1296000, 'log_id': '20240129123749239735B0529965BC6D93', 'open_id': '_000QadFMhmU1jNCI3JdPnyVDL6XavC70dFy', 'refresh_expires_in': 2592000, 'refresh_token': 'rft.c29d64456ea3d5e4c932247ee93dd735aq5OhtcYNXNFAD70XHKrdntpE6U0', 'scope': 'user_info,trial.whitelist'}
  72. '''
  73. if __name__ == "__main__":
  74. main()