From e4f7c11c282c655e670af50d1b0b50313ea6fd1e Mon Sep 17 00:00:00 2001 From: aaron <> Date: Tue, 14 Jan 2025 23:32:34 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=20=E5=BE=AE=E4=BF=A1?= =?UTF-8?q?=E8=8E=B7=E5=8F=96=E6=89=8B=E6=9C=BA=E5=8F=B7=E7=9A=84=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/api/endpoints/wechat.py | 36 ++++++++++++++++++++++++++++++ app/core/config.py | 3 +++ app/core/wechat.py | 44 +++++++++++++++++++++++++++++++++++++ app/main.py | 3 ++- 4 files changed, 85 insertions(+), 1 deletion(-) create mode 100644 app/api/endpoints/wechat.py create mode 100644 app/core/wechat.py diff --git a/app/api/endpoints/wechat.py b/app/api/endpoints/wechat.py new file mode 100644 index 0000000..415d9b6 --- /dev/null +++ b/app/api/endpoints/wechat.py @@ -0,0 +1,36 @@ +from fastapi import APIRouter, Depends +from sqlalchemy.orm import Session +from app.models.database import get_db +from app.api.deps import get_current_user +from app.models.user import UserDB +from app.core.response import success_response, error_response, ResponseModel +from app.core.wechat import WeChatClient +from pydantic import BaseModel + +router = APIRouter() + +class PhoneNumberRequest(BaseModel): + code: str # 手机号获取凭证 + +@router.post("/phone-number", response_model=ResponseModel) +async def get_phone_number( + request: PhoneNumberRequest): + """获取用户手机号 + + 通过微信获取手机号凭证换取用户手机号 + """ + try: + # 初始化微信客户端 + wechat = WeChatClient() + + # 获取用户手机号 + phone_info = await wechat.get_phone_number(request.code) + + if not phone_info or not phone_info.get('phone_number'): + return error_response(code=400, message="获取手机号失败") + + return success_response(data={ + "phone": phone_info['phone_number'] + }) + except Exception as e: + return error_response(code=500, message=f"获取手机号失败: {str(e)}") \ No newline at end of file diff --git a/app/core/config.py b/app/core/config.py index 4f99624..d4c4d91 100644 --- a/app/core/config.py +++ b/app/core/config.py @@ -56,6 +56,9 @@ class Settings(BaseSettings): {"coupon_id": 1, "count": 3}, ] + WECHAT_APPID: str = "wx3cc5b7dcb28f2756" + WECHAT_SECRET: str = "fdf03e0ff428097c2a264da50b7d804e" + class Config: case_sensitive = True env_file = ".env" diff --git a/app/core/wechat.py b/app/core/wechat.py new file mode 100644 index 0000000..fd76c32 --- /dev/null +++ b/app/core/wechat.py @@ -0,0 +1,44 @@ +import aiohttp +from app.core.config import settings + +class WeChatClient: + """微信客户端""" + + def __init__(self): + self.appid = settings.WECHAT_APPID + self.secret = settings.WECHAT_SECRET + self.access_token = None + + async def get_access_token(self): + """获取接口调用凭证""" + if self.access_token: + return self.access_token + + async with aiohttp.ClientSession() as session: + url = f"https://api.weixin.qq.com/cgi-bin/token" + params = { + "grant_type": "client_credential", + "appid": self.appid, + "secret": self.secret + } + async with session.get(url, params=params) as response: + result = await response.json() + if "access_token" in result: + self.access_token = result["access_token"] + return self.access_token + raise Exception(result.get("errmsg", "获取access_token失败")) + + async def get_phone_number(self, code: str): + """获取用户手机号""" + access_token = await self.get_access_token() + + async with aiohttp.ClientSession() as session: + url = f"https://api.weixin.qq.com/wxa/business/getuserphonenumber" + params = {"access_token": access_token} + data = {"code": code} + + async with session.post(url, params=params, json=data) as response: + result = await response.json() + if result.get("errcode") == 0: + return result.get("phone_info") + raise Exception(result.get("errmsg", "获取手机号失败")) \ No newline at end of file diff --git a/app/main.py b/app/main.py index 25c8654..dd783e4 100644 --- a/app/main.py +++ b/app/main.py @@ -1,6 +1,6 @@ from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware -from app.api.endpoints import user, address, community, station, order, coupon, community_building, upload, merchant, merchant_product, merchant_order, point, config, merchant_category, log +from app.api.endpoints import wechat,user, address, community, station, order, coupon, community_building, upload, merchant, merchant_product, merchant_order, point, config, merchant_category, log from app.models.database import Base, engine from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse @@ -30,6 +30,7 @@ app.add_middleware( app.add_middleware(RequestLoggerMiddleware) # 添加用户路由 +app.include_router(wechat.router,prefix="/wechat",tags=["微信接口"]) app.include_router(user.router, prefix="/api/user", tags=["用户"]) app.include_router(address.router, prefix="/api/address", tags=["配送地址"]) app.include_router(community.router, prefix="/api/community", tags=["社区"])