Browse Source

first commit

mrh 1 year ago
commit
a23e70a425
8 changed files with 210 additions and 0 deletions
  1. 2 0
      .gitignore
  2. 9 0
      config.py
  3. 12 0
      db/user.py
  4. 8 0
      douyin_openapi_web.http
  5. 73 0
      main.py
  6. 96 0
      readme.md
  7. 0 0
      static/douyin_open.umd.js
  8. 10 0
      static/index.html

+ 2 - 0
.gitignore

@@ -0,0 +1,2 @@
+__pycache__
+demo-release

+ 9 - 0
config.py

@@ -0,0 +1,9 @@
+
+import os
+import socket
+
+os.environ["CLIENT_KEY"] = 'aw6aipmfdtplwtyq'
+os.environ["CLIENT_SECRET"] = '53cf3dcd2663629e8a773ab59df0968b'
+
+HOST = socket.gethostbyname(socket.gethostname())
+PORT = 18888

+ 12 - 0
db/user.py

@@ -0,0 +1,12 @@
+from typing import Optional
+
+from sqlmodel import Field, SQLModel
+
+# 定义数据库模型  
+class UserOAuthToken(SQLModel, table=True):  
+    id = Field(default=None, primary_key=True)
+    access_token:str
+    expires_in: Optional[int] = None
+    open_id:str
+    refresh_expires_in: Optional[int] = None
+    refresh_token:str

+ 8 - 0
douyin_openapi_web.http

@@ -0,0 +1,8 @@
+# WEB扫码接入 参考 https://developer.open-douyin.com/docs/resource/zh-CN/dop/develop/sdk/web-app/web/permission
+# 打开链接,扫码登录 
+GET https://open.douyin.com/platform/oauth/connect/?client_key=aw6aipmfdtplwtyq&response_type=code&scope=user_info,renew_refresh_token,trial.whitelist&redirect_uri=https://open-douyin.magong.site/verify_callback HTTP/1.1  
+Host: open.douyin.com
+
+# 服务器收到返回信息
+GET /verify_callback?code=936c3671e073703cnzV93iYzyWbdLIZmFPQJ&state=&scopes=user_info,trial.whitelist HTTP/1.1
+

+ 73 - 0
main.py

@@ -0,0 +1,73 @@
+import socket
+from fastapi import FastAPI, Request  
+from fastapi.responses import HTMLResponse  
+from fastapi.staticfiles import StaticFiles  
+from fastapi.templating import Jinja2Templates
+import requests  
+import uvicorn
+from fastapi.responses import FileResponse  
+from fastapi import FastAPI, Depends, HTTPException, Form  
+import httpx
+import os
+from db.user import UserOAuthToken
+from config import HOST, PORT
+
+app = FastAPI()  
+  
+@app.get("/")  
+async def read_root(request: Request):  
+    return FileResponse(os.path.join("static", "index.html"))  
+
+# 授权码获取 access_token 的路由  
+@app.post("/get_access_token")  
+async def get_access_token(request: Request):  
+    client_key = os.environ.get("CLIENT_KEY")  # 从环境变量中获取 client_key  
+    client_secret = os.environ.get("CLIENT_SECRET")  # 从环境变量中获取 client_secret  
+    try:  
+        code = request.query_params["code"]  # 从查询参数中获取 code  
+    except KeyError:  
+        raise HTTPException(status_code=400, detail="Missing 'code' parameter")  
+  
+    # 发送请求获取 access_token  
+    async with httpx.AsyncClient() as client:  
+        response = await client.post(  
+            "https://open.douyin.com/oauth/access_token/",  
+            headers={"Content-Type": "application/json"},  
+            json={  
+                "grant_type": "authorization_code",  
+                "client_key": client_key,  
+                "client_secret": client_secret,  
+                "code": code,  
+            },  
+        )  
+  
+    if response.status_code != 200:  
+        raise HTTPException(status_code=response.status_code, detail=response.text)  
+  
+    data = response.json()["data"]  
+  
+    print(data)
+  
+    return {"message": "Access token stored successfully"}  
+
+@app.get("/verify_callback")  
+async def verify_callback(request: Request):  
+    # 打印请求方法  
+    print(f"Method: {request.method}")  
+      
+    # 打印请求头  
+    print(f"Headers:")  
+    for key, value in request.headers.items():  
+        print(f"{key}: {value}")  
+
+    # 打印查询参数  
+    print(f"Query Parameters:")  
+    for key, value in request.query_params.items():  
+        print(f"{key}: {value}")  
+    return HTMLResponse("<h1>Callback Received! Verification Successful.</h1>")
+
+def main():
+    uvicorn.run(app, host=HOST, port=PORT, log_level="info")
+
+if __name__ == "__main__":
+    main()

+ 96 - 0
readme.md

@@ -0,0 +1,96 @@
+
+```shell
+# WEB扫码接入 参考 https://developer.open-douyin.com/docs/resource/zh-CN/dop/develop/sdk/web-app/web/permission
+# 打开链接,扫码登录 
+GET https://open.douyin.com/platform/oauth/connect/?client_key=aw6aipmfdtplwtyq&response_type=code&scope=user_info,renew_refresh_token,trial.whitelist&redirect_uri=https://api.magong.site/verify_callback HTTP/1.1  
+Host: open.douyin.com
+
+# 服务器收到返回信息。程序员马工
+GET /verify_callback?code=936c3671e073703cnzV93iYzyWbdLIZmFPQJ&state=&scopes=user_info,trial.whitelist HTTP/1.1
+# 渣渣辉
+GET /verify_callback?code=676a1101ea02bc5dTaUVtKg8c5enYaGqB4dT&state=&scopes=user_info,trial.whitelist HTTP/1.1
+```
+
+GPT:
+以下是接口文档:
+步骤一:获取授权码 code
+请求示例:
+https://open.douyin.com/platform/oauth/connect?client_key=awf4xgy8cibvhzuv&response_type=code&scope=user_info&redirect_uri=https://api.magong.site/verify_callback
+成功示例:
+GET /verify_callback?code=676a1101ea02bc5dTaUVtKg8c5enYaGqB4dT&state=&scopes=user_info,trial.whitelist HTTP/1.1
+
+
+步骤二:通过授权码 code 获取 access_token
+HTTP URL
+https://open.douyin.com/oauth/access_token/
+HTTP Method
+POST
+Content-Type string "application/json"
+请求示例
+curl --location 'https://open.douyin.com/oauth/access_token/' \
+--header 'Content-Type: application/json' \
+--data '{
+    "grant_type": "authorization_code",
+    "client_key": "aw05az2qjv4b****",
+    "client_secret": "7802f4e6f243e659d51135445fe******",
+    "code": "676a1101ea02bc5dTaUVtKg8c5enYaGqB4dT"
+}'
+响应示例
+{
+    "data": {
+        "access_token": "act.f7094fbffab2ecbfc45e9af9c32bc241oYdckvBKe82BPx8T******",
+        "captcha": "",
+        "desc_url": "",
+        "description": "",
+        "error_code": 0,
+        "expires_in": 1296000,
+        "log_id": "20230525105733ED3ED7AC56A******",
+        "open_id": "b9b71865-7fea-44cc-******",
+        "refresh_expires_in": 2592000,
+        "refresh_token": "rft.713900b74edde9f30ec4e246b706da30t******",
+        "scope": "user_info"
+    },
+    "message": "success"
+}
+异常示例
+{
+  "data": {
+    "description": "Parameter error",
+    "error_code": 2100005
+  },
+  "extra": {
+    "logid": "2020070614111601022506808001045D59",
+    "now": 1594015876138
+  }
+}
+
+以下是我的代码:
+```python
+app = FastAPI()  
+  
+@app.get("/")  
+async def read_root(request: Request):  
+    return FileResponse(os.path.join("static", "index.html"))  
+
+@app.get("/jsbridge")  
+async def verify_callback(request: Request):  
+    return FileResponse(os.path.join("static", "douyin_open.umd.js"))  
+
+@app.get("/verify_callback")  
+async def verify_callback(request: Request):  
+    # 打印请求方法  
+    print(f"Method: {request.method}")  
+      
+    # 打印请求头  
+    print(f"Headers:")  
+    for key, value in request.headers.items():  
+        print(f"{key}: {value}")  
+
+    # 打印查询参数  
+    print(f"Query Parameters:")  
+    for key, value in request.query_params.items():  
+        print(f"{key}: {value}")  
+    return HTMLResponse("<h1>Callback Received! Verification Successful.</h1>")
+
+```
+用 Fastapi fastapi_amis_admin 完成以上文档功能。将 verify_callback 获得的 code 获取 access_token 。然后将 access_token 、 expires_in、open_id、refresh_expires_in、refresh_token 存入数据库。不要给太多说明,直接写代码

File diff suppressed because it is too large
+ 0 - 0
static/douyin_open.umd.js


+ 10 - 0
static/index.html

@@ -0,0 +1,10 @@
+<!DOCTYPE html>  
+<html>  
+<head>  
+    <title>FastAPI Callback Verification</title>  
+</head>  
+<body>  
+    <h1>Welcome to the FastAPI Callback Verification Page</h1>  
+    <p>This is the homepage for callback verification.</p>  
+</body>  
+</html>

Some files were not shown because too many files changed in this diff