feat(mini-auth): add WeChat service-account bind APIs
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
405808f4dd
commit
80722d76db
3 files changed
+174
No files matched your search
@@ -20,6 +20,7 @@ from app.services.wechat_mini_auth import (
|
||||
code2session,
|
||||
get_phone_number,
|
||||
)
|
||||
from app.services.wechat_mp_auth import WechatMpAuthError, oauth_code_to_openid
|
||||
|
||||
|
||||
router = APIRouter(prefix="/mini/auth", tags=["小程序鉴权"])
|
||||
@@ -120,3 +121,49 @@ async def wechat_bind(
|
||||
db.add(user)
|
||||
db.commit()
|
||||
return success_response({"bound": True, "message": "绑定成功"})
|
||||
|
||||
|
||||
@router.get("/mp-bind-status", response_model=dict)
|
||||
async def mp_bind_status(request: Request, db: Session = Depends(get_db)):
|
||||
"""当前用户是否已绑定微信服务号 openid。"""
|
||||
try:
|
||||
user_id = await _resolve_user_id(request, db)
|
||||
except HTTPException:
|
||||
return error_response(401, "未授权")
|
||||
|
||||
user = user_crud.get(db, user_id)
|
||||
bound = bool(user and (getattr(user, "wx_mp_openid", None) or "").strip())
|
||||
return success_response({"bound": bound})
|
||||
|
||||
|
||||
@router.post("/mp-bind", response_model=dict)
|
||||
async def mp_bind(request: Request, body: dict, db: Session = Depends(get_db)):
|
||||
"""服务号网页授权 code 绑定当前用户(需 Bearer)。"""
|
||||
try:
|
||||
user_id = await _resolve_user_id(request, db)
|
||||
except HTTPException:
|
||||
return error_response(401, "未授权")
|
||||
|
||||
code = (body.get("code") or "").strip()
|
||||
try:
|
||||
info = oauth_code_to_openid(code)
|
||||
except WechatMpAuthError as exc:
|
||||
return error_response(400, str(exc))
|
||||
|
||||
mp_openid = info["openid"]
|
||||
other = user_crud.get_by_wx_mp_openid(db, mp_openid)
|
||||
if other and other.id != user_id:
|
||||
return error_response(409, "该微信服务号已绑定其他账号")
|
||||
|
||||
user = user_crud.get(db, user_id)
|
||||
if not user or user.del_flag != 0:
|
||||
return error_response(401, "用户不存在")
|
||||
|
||||
user.wx_mp_openid = mp_openid
|
||||
if info.get("unionid"):
|
||||
user.wx_unionid = info["unionid"]
|
||||
user.wx_mp_bind_time = datetime.now()
|
||||
user.update_time = datetime.now()
|
||||
db.add(user)
|
||||
db.commit()
|
||||
return success_response({"bound": True})
|
||||
Reference in new issue
Block a user