增加 微信获取手机号的接口。
This commit is contained in:
parent
13c7ab3655
commit
e4f7c11c28
36
app/api/endpoints/wechat.py
Normal file
36
app/api/endpoints/wechat.py
Normal file
@ -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)}")
|
||||
@ -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"
|
||||
|
||||
44
app/core/wechat.py
Normal file
44
app/core/wechat.py
Normal file
@ -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", "获取手机号失败"))
|
||||
@ -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=["社区"])
|
||||
|
||||
Loading…
Reference in New Issue
Block a user