添加后端API和前端项目的初始目录结构,包括应用层模块、工具模块和模型定义 配置前后端的.dockerignore文件以排除开发环境文件 添加前端样式文件,包括字体、Tailwind CSS和主题配置 初始化Python虚拟环境中的类型标记文件
27 lines
786 B
Python
27 lines
786 B
Python
import httpx
|
|
|
|
from app.config import settings
|
|
|
|
|
|
async def code_to_session(code: str) -> dict:
|
|
"""用小程序 code 换取 openid 和 session_key"""
|
|
url = "https://api.weixin.qq.com/sns/jscode2session"
|
|
params = {
|
|
"appid": settings.wechat_app_id,
|
|
"secret": settings.wechat_app_secret,
|
|
"js_code": code,
|
|
"grant_type": "authorization_code",
|
|
}
|
|
async with httpx.AsyncClient() as client:
|
|
resp = await client.get(url, params=params)
|
|
data = resp.json()
|
|
|
|
if "errcode" in data and data["errcode"] != 0:
|
|
raise Exception(f"微信登录失败: {data.get('errmsg', '未知错误')}")
|
|
|
|
return {
|
|
"openid": data["openid"],
|
|
"session_key": data["session_key"],
|
|
"unionid": data.get("unionid"),
|
|
}
|