Merge branch 'main' into feature/coupon-claim-integration
把 main 的"美团 CPS 模块 + 后端分层重构(integrations/repositories)"合入领券分支。 解决 3 处冲突(均为两边各自新增, 保留双方): - app/main.py: 同时注册 coupon_router 与 meituan_router - app/core/config.py: 同时保留 PRICEBOT_* 与 MT_CPS_* 配置 - .env.example: 同上 coupon.py 本身无冲突(仅依赖 deps.CurrentUser 与 core.config, 重构未触及)。 Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -34,6 +34,13 @@ SMS_MOCK=true
|
||||
SMS_CODE_TTL_SEC=300
|
||||
SMS_SEND_INTERVAL_SEC=60
|
||||
|
||||
# ===== 美团联盟 CPS =====
|
||||
# 美团联盟后台 → 媒体管理 拿到的 appkey 和密钥
|
||||
MT_CPS_APP_KEY=
|
||||
MT_CPS_APP_SECRET=
|
||||
# 默认渠道追踪标识(sid),用于区分不同 app 的 CPS 数据
|
||||
MT_CPS_DEFAULT_SID=sgbjia
|
||||
|
||||
# ===== Pricebot 上游 (领券业务透传目标) =====
|
||||
# 客户端调本服务的 /api/v1/coupon/step,我们透传到 pricebot-backend 的 /api/coupon/step。
|
||||
# 本地开发用 localhost:8000。生产部署改成内网地址(如 http://pricebot.internal:8000)。
|
||||
|
||||
@@ -34,3 +34,6 @@ secrets/*
|
||||
.idea/
|
||||
.vscode/
|
||||
*.swp
|
||||
|
||||
# 运行日志(run.sh 输出, 不入库)
|
||||
*.log
|
||||
|
||||
+6
-6
@@ -15,10 +15,10 @@ import logging
|
||||
from fastapi import APIRouter, HTTPException, status
|
||||
|
||||
from app.api.deps import CurrentUser, DbSession
|
||||
from app.core.jiguang import JiguangError, mask_phone, verify_and_get_phone
|
||||
from app.core.security import TokenError, decode_token, issue_token_pair
|
||||
from app.core.sms import SmsError, send_code, verify_code
|
||||
from app.crud import user as crud_user
|
||||
from app.integrations.jiguang import JiguangError, mask_phone, verify_and_get_phone
|
||||
from app.integrations.sms import SmsError, send_code, verify_code
|
||||
from app.repositories import user as user_repo
|
||||
from app.schemas.auth import (
|
||||
JverifyLoginRequest,
|
||||
LogoutResponse,
|
||||
@@ -61,7 +61,7 @@ def jverify_login(req: JverifyLoginRequest, db: DbSession) -> TokenWithUser:
|
||||
logger.error("[JG] verify+decrypt failed: %s", e, exc_info=True)
|
||||
raise HTTPException(status_code=502, detail=f"jiguang verify failed: {e}") from e
|
||||
|
||||
user = crud_user.upsert_user_for_login(db, phone=phone, register_channel="jverify")
|
||||
user = user_repo.upsert_user_for_login(db, phone=phone, register_channel="jverify")
|
||||
if user.status != "active":
|
||||
raise HTTPException(status_code=403, detail="account disabled")
|
||||
|
||||
@@ -88,7 +88,7 @@ def sms_login(req: SmsLoginRequest, db: DbSession) -> TokenWithUser:
|
||||
if not verify_code(req.phone, req.code):
|
||||
raise HTTPException(status_code=400, detail="invalid sms code")
|
||||
|
||||
user = crud_user.upsert_user_for_login(db, phone=req.phone, register_channel="sms")
|
||||
user = user_repo.upsert_user_for_login(db, phone=req.phone, register_channel="sms")
|
||||
if user.status != "active":
|
||||
raise HTTPException(status_code=403, detail="account disabled")
|
||||
|
||||
@@ -106,7 +106,7 @@ def refresh(req: RefreshRequest, db: DbSession) -> TokenPair:
|
||||
raise HTTPException(status_code=401, detail=str(e)) from e
|
||||
|
||||
user_id = int(payload["sub"])
|
||||
user = crud_user.get_user_by_id(db, user_id)
|
||||
user = user_repo.get_user_by_id(db, user_id)
|
||||
if user is None or user.status != "active":
|
||||
raise HTTPException(status_code=401, detail="user not found or disabled")
|
||||
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
"""美团 CPS 券列表 + 换链。
|
||||
|
||||
不需要登录,客户端传经纬度即可。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
|
||||
from app.integrations.meituan import MeituanCpsError, get_referral_link, query_coupon
|
||||
from app.schemas.meituan import (
|
||||
CouponCard,
|
||||
CouponListRequest,
|
||||
CouponListResponse,
|
||||
FeedRequest,
|
||||
FeedResponse,
|
||||
ReferralLinkRequest,
|
||||
ReferralLinkResponse,
|
||||
)
|
||||
|
||||
logger = logging.getLogger("shagua.meituan")
|
||||
|
||||
router = APIRouter(prefix="/api/v1/meituan", tags=["meituan-cps"])
|
||||
|
||||
|
||||
@router.post("/coupons", response_model=CouponListResponse, summary="券列表(为您推荐)")
|
||||
def list_coupons(req: CouponListRequest) -> CouponListResponse:
|
||||
logger.info("[coupons] lon=%.6f lat=%.6f topic=%s", req.longitude, req.latitude, req.list_topic_id)
|
||||
try:
|
||||
raw = query_coupon(
|
||||
longitude=req.longitude,
|
||||
latitude=req.latitude,
|
||||
platform=req.platform,
|
||||
biz_line=req.biz_line,
|
||||
list_topic_id=req.list_topic_id,
|
||||
search_text=req.keyword,
|
||||
search_id=req.search_id,
|
||||
sort_field=req.sort_field,
|
||||
page_no=req.page,
|
||||
page_size=req.page_size,
|
||||
)
|
||||
except MeituanCpsError as e:
|
||||
logger.error("query_coupon failed: %s", e)
|
||||
raise HTTPException(status_code=502, detail=f"meituan: {e}") from e
|
||||
|
||||
items = [CouponCard.from_raw(it) for it in (raw.get("data") or [])]
|
||||
return CouponListResponse(
|
||||
items=items,
|
||||
has_next=raw.get("hasNext", False),
|
||||
search_id=raw.get("searchId"),
|
||||
)
|
||||
|
||||
|
||||
_TOPIC_ROUNDS = [
|
||||
(3, 3), # 爆款筛选
|
||||
(2, 2), # 今日必推
|
||||
(1, 5), # 精选 + 限时筛选
|
||||
]
|
||||
|
||||
def _interleave(waimai: list[dict], daodian: list[dict]) -> list[CouponCard]:
|
||||
items: list[CouponCard] = []
|
||||
seen: set[str] = set()
|
||||
i = j = 0
|
||||
while i < len(waimai) or j < len(daodian):
|
||||
for _ in range(2):
|
||||
if i < len(waimai):
|
||||
card = CouponCard.from_raw(waimai[i]); i += 1
|
||||
if card.product_view_sign not in seen:
|
||||
seen.add(card.product_view_sign); items.append(card)
|
||||
if j < len(daodian):
|
||||
card = CouponCard.from_raw(daodian[j]); j += 1
|
||||
if card.product_view_sign not in seen:
|
||||
seen.add(card.product_view_sign); items.append(card)
|
||||
return items
|
||||
|
||||
|
||||
@router.post("/feed", response_model=FeedResponse, summary="混合feed(外卖+到店交叉, 无限流)")
|
||||
def feed(req: FeedRequest) -> FeedResponse:
|
||||
page_idx = req.page - 1
|
||||
lon, lat = req.longitude, req.latitude
|
||||
logger.info("[feed] page=%s lon=%.6f lat=%.6f", req.page, lon, lat)
|
||||
|
||||
def _fetch_topic(platform: int, biz_line: int | None, topic: int) -> list[dict]:
|
||||
try:
|
||||
return (query_coupon(
|
||||
longitude=lon, latitude=lat,
|
||||
platform=platform, biz_line=biz_line,
|
||||
list_topic_id=topic, page_size=20,
|
||||
).get("data") or [])
|
||||
except MeituanCpsError:
|
||||
return []
|
||||
|
||||
if page_idx >= len(_TOPIC_ROUNDS):
|
||||
return FeedResponse(items=[], has_next=False, page=req.page)
|
||||
|
||||
wm_topic, dd_topic = _TOPIC_ROUNDS[page_idx]
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||
f_wm = pool.submit(_fetch_topic, 1, None, wm_topic)
|
||||
f_dd = pool.submit(_fetch_topic, 2, 1, dd_topic)
|
||||
waimai, daodian = f_wm.result(), f_dd.result()
|
||||
|
||||
items = _interleave(waimai, daodian)
|
||||
has_next = page_idx + 1 < len(_TOPIC_ROUNDS)
|
||||
return FeedResponse(items=items, has_next=has_next, page=req.page)
|
||||
|
||||
|
||||
@router.post("/referral-link", response_model=ReferralLinkResponse, summary="换取推广链接(点抢时调)")
|
||||
def referral_link(req: ReferralLinkRequest) -> ReferralLinkResponse:
|
||||
try:
|
||||
raw = get_referral_link(
|
||||
product_view_sign=req.product_view_sign,
|
||||
platform=req.platform,
|
||||
biz_line=req.biz_line,
|
||||
sid=req.sid,
|
||||
link_type_list=req.link_type_list,
|
||||
)
|
||||
except MeituanCpsError as e:
|
||||
logger.error("get_referral_link failed: %s", e)
|
||||
raise HTTPException(status_code=502, detail=f"meituan: {e}") from e
|
||||
|
||||
link_map = raw.get("referralLinkMap") or {}
|
||||
link = raw.get("data") or link_map.get("1") or link_map.get("3") or next(iter(link_map.values()), "")
|
||||
return ReferralLinkResponse(link=link, link_map=link_map)
|
||||
+11
-1
@@ -6,15 +6,18 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import Field
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
_PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(
|
||||
env_file=".env",
|
||||
env_file=str(_PROJECT_ROOT / ".env"),
|
||||
env_file_encoding="utf-8",
|
||||
case_sensitive=False,
|
||||
extra="ignore",
|
||||
@@ -46,6 +49,13 @@ class Settings(BaseSettings):
|
||||
SMS_CODE_TTL_SEC: int = 300
|
||||
SMS_SEND_INTERVAL_SEC: int = 60
|
||||
|
||||
# ===== 美团联盟 CPS =====
|
||||
MT_CPS_APP_KEY: str = ""
|
||||
MT_CPS_APP_SECRET: str = ""
|
||||
MT_CPS_HOST: str = "https://media.meituan.com"
|
||||
MT_CPS_TIMEOUT_SEC: int = 15
|
||||
MT_CPS_DEFAULT_SID: str = "sgbjia"
|
||||
|
||||
# ===== Pricebot 上游 (领券业务透传目标) =====
|
||||
# pricebot-backend 默认跑在 8000。/api/v1/coupon/step 会透传到这里的 /api/coupon/step
|
||||
PRICEBOT_BASE_URL: str = "http://localhost:8000"
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
"""美团联盟 CPS 开放接口客户端。
|
||||
|
||||
签名方式:类阿里云网关 S-Ca 头,但 stringToSign **只有 4 段**——
|
||||
METHOD\n + Content-MD5\n + Headers + Url
|
||||
没有 Accept / Content-Type / Date 行(加了就签名失败)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from app.core.config import settings
|
||||
|
||||
logger = logging.getLogger("shagua.meituan")
|
||||
|
||||
|
||||
class MeituanCpsError(Exception):
|
||||
"""美团 CPS 接口调用失败。"""
|
||||
|
||||
|
||||
def _content_md5(body: bytes) -> str:
|
||||
return base64.b64encode(hashlib.md5(body).digest()).decode()
|
||||
|
||||
|
||||
def _sign(secret: str, method: str, content_md5: str, path: str,
|
||||
signed_headers: dict[str, str]) -> str:
|
||||
block = "".join(
|
||||
f"{k}:{signed_headers[k]}\n"
|
||||
for k in sorted(signed_headers)
|
||||
)
|
||||
sts = f"{method}\n{content_md5}\n{block}{path}"
|
||||
return base64.b64encode(
|
||||
hmac.new(secret.encode(), sts.encode(), hashlib.sha256).digest()
|
||||
).decode()
|
||||
|
||||
|
||||
def _call(path: str, body_obj: dict[str, Any]) -> dict[str, Any]:
|
||||
if not settings.MT_CPS_APP_KEY or not settings.MT_CPS_APP_SECRET:
|
||||
raise MeituanCpsError("MT_CPS_APP_KEY / MT_CPS_APP_SECRET not configured")
|
||||
|
||||
body = json.dumps(body_obj, ensure_ascii=False).encode("utf-8")
|
||||
content_md5 = _content_md5(body)
|
||||
ts = str(int(time.time() * 1000))
|
||||
|
||||
signed_headers = {"S-Ca-App": settings.MT_CPS_APP_KEY, "S-Ca-Timestamp": ts}
|
||||
signature = _sign(settings.MT_CPS_APP_SECRET, "POST", content_md5, path, signed_headers)
|
||||
|
||||
headers = {
|
||||
"Content-Type": "application/json",
|
||||
"Content-MD5": content_md5,
|
||||
"S-Ca-App": settings.MT_CPS_APP_KEY,
|
||||
"S-Ca-Timestamp": ts,
|
||||
"S-Ca-Signature-Headers": "S-Ca-Timestamp,S-Ca-App",
|
||||
"S-Ca-Signature": signature,
|
||||
}
|
||||
|
||||
url = f"{settings.MT_CPS_HOST}{path}"
|
||||
try:
|
||||
resp = httpx.post(url, content=body, headers=headers, timeout=settings.MT_CPS_TIMEOUT_SEC)
|
||||
except httpx.HTTPError as e:
|
||||
logger.exception("[MT] http error calling %s", url)
|
||||
raise MeituanCpsError(f"meituan http error: {e}") from e
|
||||
|
||||
if resp.status_code != 200:
|
||||
logger.error("[MT] HTTP %s body=%s", resp.status_code, resp.text[:500])
|
||||
raise MeituanCpsError(f"meituan http {resp.status_code}")
|
||||
|
||||
data = resp.json()
|
||||
if data.get("code") != 0:
|
||||
logger.error("[MT] api error code=%s message=%s", data.get("code"), data.get("message"))
|
||||
raise MeituanCpsError(f"code={data.get('code')} {data.get('message')}")
|
||||
|
||||
return data
|
||||
|
||||
|
||||
# ────────────────────── 业务方法 ──────────────────────
|
||||
|
||||
def query_coupon(
|
||||
*,
|
||||
longitude: float,
|
||||
latitude: float,
|
||||
platform: int = 1,
|
||||
biz_line: int | None = None,
|
||||
list_topic_id: int | None = 3,
|
||||
search_text: str | None = None,
|
||||
search_id: str | None = None,
|
||||
sort_field: int | None = None,
|
||||
page_no: int = 1,
|
||||
page_size: int = 20,
|
||||
) -> dict[str, Any]:
|
||||
body: dict[str, Any] = {
|
||||
"platform": platform,
|
||||
"longitude": int(longitude * 1_000_000),
|
||||
"latitude": int(latitude * 1_000_000),
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
if biz_line is not None:
|
||||
body["bizLine"] = biz_line
|
||||
|
||||
if search_text:
|
||||
body["searchText"] = search_text
|
||||
if sort_field is None:
|
||||
sort_field = 6
|
||||
elif list_topic_id is not None:
|
||||
body["listTopiId"] = list_topic_id
|
||||
|
||||
if sort_field is not None:
|
||||
body["sortField"] = sort_field
|
||||
if search_id:
|
||||
body["searchId"] = search_id
|
||||
|
||||
return _call("/cps_open/common/api/v1/query_coupon", body)
|
||||
|
||||
|
||||
def get_referral_link(
|
||||
*,
|
||||
product_view_sign: str,
|
||||
platform: int = 1,
|
||||
biz_line: int | None = None,
|
||||
sid: str | None = None,
|
||||
link_type_list: list[int] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
body: dict[str, Any] = {"productViewSign": product_view_sign}
|
||||
if platform == 2:
|
||||
body["platform"] = 2
|
||||
if biz_line is not None:
|
||||
body["bizLine"] = biz_line
|
||||
|
||||
body["sid"] = sid or settings.MT_CPS_DEFAULT_SID
|
||||
body["linkTypeList"] = link_type_list or [1, 3]
|
||||
|
||||
return _call("/cps_open/common/api/v1/get_referral_link", body)
|
||||
@@ -13,6 +13,7 @@ from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from app.api.v1.auth import router as auth_router
|
||||
from app.api.v1.coupon import router as coupon_router
|
||||
from app.api.v1.meituan import router as meituan_router
|
||||
from app.core.config import settings
|
||||
from app.core.logging import setup_logging
|
||||
|
||||
@@ -59,3 +60,4 @@ def health() -> dict[str, str]:
|
||||
|
||||
app.include_router(auth_router)
|
||||
app.include_router(coupon_router)
|
||||
app.include_router(meituan_router)
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
"""美团 CPS 券列表 / 换链相关 schemas。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
# ───────────────── 券卡片(归一化后给客户端) ─────────────────
|
||||
|
||||
class CouponCard(BaseModel):
|
||||
product_view_sign: str
|
||||
platform: int = Field(..., description="1=外卖/到家, 2=到店")
|
||||
biz_line: int | None = Field(None, description="到店子类: 1到餐 2到综 3酒店 4门票")
|
||||
|
||||
name: str
|
||||
head_image_url: str
|
||||
brand_name: str | None = None
|
||||
brand_logo_url: str | None = None
|
||||
|
||||
sell_price: str
|
||||
original_price: str
|
||||
discount_amount: str = Field(..., description="优惠金额 = 原价 - 现价")
|
||||
|
||||
commission_rate: str = Field(..., description="佣金比例, 如 1.4%")
|
||||
commission_amount: str | None = Field(None, description="预估佣金元")
|
||||
|
||||
sale_volume: str | None = None
|
||||
poi_name: str | None = Field(None, description="最近门店名")
|
||||
distance_text: str | None = Field(None, description="格式化距离, 如 600m / 1.5km")
|
||||
distance_meters: float | None = Field(None, description="原始距离(米)")
|
||||
available_poi_num: int | None = Field(None, description="可用门店数")
|
||||
|
||||
coupon_num: int | None = Field(None, description="券张数(外卖兑换券)")
|
||||
valid_days: int | None = Field(None, description="券有效天数")
|
||||
price_label: str | None = Field(None, description="如 15天低价")
|
||||
rank_label: str | None = Field(None, description="如 2小时北京外卖销量榜第1名")
|
||||
rating_label: str | None = Field(None, description="如 4.6分")
|
||||
|
||||
@classmethod
|
||||
def from_raw(cls, item: dict[str, Any]) -> CouponCard:
|
||||
cpd = item.get("couponPackDetail") or {}
|
||||
brand = item.get("brandInfo") or {}
|
||||
comm = item.get("commissionInfo") or {}
|
||||
poi = item.get("deliverablePoiInfo") or {}
|
||||
avail = item.get("availablePoiInfo") or {}
|
||||
label = cpd.get("productLabel") or {}
|
||||
price_lbl = label.get("pricePowerLabel") or {}
|
||||
valid_info = item.get("couponValidTimeInfo") or {}
|
||||
|
||||
platform = cpd.get("platform") or 1
|
||||
biz_line = cpd.get("bizLine")
|
||||
|
||||
head_url = cpd.get("headUrl") or ""
|
||||
if "@" in head_url:
|
||||
head_url = head_url.split("@")[0]
|
||||
|
||||
sell = cpd.get("sellPrice") or "0"
|
||||
orig = cpd.get("originalPrice") or "0"
|
||||
try:
|
||||
discount = f"{float(orig) - float(sell):.2f}"
|
||||
except (ValueError, TypeError):
|
||||
discount = "0"
|
||||
|
||||
cp = comm.get("commissionPercent") or "0"
|
||||
try:
|
||||
rate = f"{float(cp) / 100:.1f}%"
|
||||
except (ValueError, TypeError):
|
||||
rate = "0%"
|
||||
|
||||
raw_dist = poi.get("deliveryDistance")
|
||||
dist_meters: float | None = None
|
||||
dist_text: str | None = None
|
||||
if raw_dist not in (None, "null", ""):
|
||||
try:
|
||||
d = float(raw_dist)
|
||||
dist_meters = d * 1000 if platform == 1 else d
|
||||
if dist_meters < 1000:
|
||||
dist_text = f"{int(dist_meters)}m"
|
||||
else:
|
||||
dist_text = f"{dist_meters / 1000:.1f}km"
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
return cls(
|
||||
product_view_sign=cpd.get("productViewSign") or cpd.get("skuViewId") or "",
|
||||
platform=platform,
|
||||
biz_line=biz_line,
|
||||
name=cpd.get("name") or "",
|
||||
head_image_url=head_url,
|
||||
brand_name=brand.get("brandName"),
|
||||
brand_logo_url=brand.get("brandLogoUrl"),
|
||||
sell_price=sell,
|
||||
original_price=orig,
|
||||
discount_amount=discount,
|
||||
commission_rate=rate,
|
||||
commission_amount=comm.get("commission"),
|
||||
sale_volume=cpd.get("saleVolume"),
|
||||
poi_name=poi.get("poiName"),
|
||||
distance_text=dist_text,
|
||||
distance_meters=dist_meters,
|
||||
available_poi_num=avail.get("availablePoiNum"),
|
||||
coupon_num=cpd.get("couponNum"),
|
||||
valid_days=valid_info.get("couponValidDay"),
|
||||
price_label=price_lbl.get("historyPriceLabel") or price_lbl.get("beatMTLabel"),
|
||||
rank_label=label.get("productRankLabel"),
|
||||
rating_label=label.get("dianPingRankLabel"),
|
||||
)
|
||||
|
||||
|
||||
# ───────────────── 券列表 请求 / 响应 ─────────────────
|
||||
|
||||
class CouponListRequest(BaseModel):
|
||||
longitude: float = Field(..., description="经度, 如 116.404")
|
||||
latitude: float = Field(..., description="纬度, 如 39.928")
|
||||
platform: int = Field(1, description="1=外卖/到家, 2=到店")
|
||||
biz_line: int | None = Field(None, description="到店子类: 1到餐 2到综 3酒店 4门票; 外卖不填")
|
||||
list_topic_id: int | None = Field(3, description="榜单: 1精选 2今日必推 3爆款筛选 5限时筛选")
|
||||
keyword: str | None = Field(None, description="搜索关键词(填了会忽略 list_topic_id)")
|
||||
sort_field: int | None = Field(None, description="1价格 2销量 6离我最近; 搜索默认6")
|
||||
search_id: str | None = Field(None, description="翻页token, 首页不填")
|
||||
page: int = Field(1, ge=1)
|
||||
page_size: int = Field(20, ge=1, le=20)
|
||||
|
||||
|
||||
class CouponListResponse(BaseModel):
|
||||
items: list[CouponCard]
|
||||
has_next: bool = False
|
||||
search_id: str | None = None
|
||||
|
||||
|
||||
class FeedRequest(BaseModel):
|
||||
longitude: float = Field(..., description="经度")
|
||||
latitude: float = Field(..., description="纬度")
|
||||
page: int = Field(1, ge=1)
|
||||
page_size: int = Field(20, ge=1, le=20)
|
||||
|
||||
|
||||
class FeedResponse(BaseModel):
|
||||
items: list[CouponCard]
|
||||
has_next: bool = False
|
||||
page: int = 1
|
||||
|
||||
|
||||
# ───────────────── 换链 请求 / 响应 ─────────────────
|
||||
|
||||
class ReferralLinkRequest(BaseModel):
|
||||
product_view_sign: str = Field(..., min_length=1)
|
||||
platform: int = Field(1, description="1=外卖/到家, 2=到店")
|
||||
biz_line: int | None = None
|
||||
sid: str | None = Field(None, description="渠道追踪标识, 不填用默认")
|
||||
link_type_list: list[int] | None = Field(None, description="1=H5长链 2=H5短链 3=deeplink; 不填默认[1,3]")
|
||||
|
||||
|
||||
class ReferralLinkResponse(BaseModel):
|
||||
link: str = Field(..., description="默认推广链接")
|
||||
link_map: dict[str, str] = Field(default_factory=dict, description="各类型链接 {linkType: url}")
|
||||
+248
@@ -0,0 +1,248 @@
|
||||
# 傻瓜比价 App 后端 — API 接口文档
|
||||
|
||||
> Base URL:生产 `https://app-api.shaguabijia.com`;本地联调 `http://<开发机>:8770`
|
||||
> 协议:HTTP / JSON,请求与响应体均 `application/json`,字段统一 **snake_case**
|
||||
> 鉴权:需鉴权的接口在请求头带 `Authorization: Bearer <access_token>`
|
||||
> 最后更新:2026-05-27
|
||||
|
||||
---
|
||||
|
||||
## 通用约定
|
||||
|
||||
- **时间格式**:ISO 8601 UTC(如 `2026-05-27T12:34:56Z`)
|
||||
- **错误响应**:FastAPI 标准结构 `{"detail": "<错误信息>"}`,配合语义化 HTTP 状态码:
|
||||
- `400` 业务参数错(如验证码不对)
|
||||
- `401` 未认证 / token 无效或过期 / 用户被禁(响应头带 `WWW-Authenticate: Bearer`)
|
||||
- `403` 账号被禁用
|
||||
- `422` 请求体字段校验失败(FastAPI 自动校验,如手机号格式)
|
||||
- `429` 触发限流(短信发送过频)
|
||||
- `502` 上游调用失败(极光验证/解密失败、美团接口失败)
|
||||
- **接口文档(交互式)**:`APP_ENV` 非 prod 时开放 `GET /docs`(Swagger UI)、`GET /redoc`;生产环境关闭。
|
||||
|
||||
---
|
||||
|
||||
## 接口总览
|
||||
|
||||
| # | 方法 + 路径 | 鉴权 | 说明 |
|
||||
|---|---|---|---|
|
||||
| 1 | `GET /health` | 无 | 健康检查 |
|
||||
| 2 | `POST /api/v1/auth/jverify-login` | 无 | 极光一键登录 |
|
||||
| 3 | `POST /api/v1/auth/sms/send` | 无 | 发送短信验证码(mock) |
|
||||
| 4 | `POST /api/v1/auth/sms/login` | 无 | 手机号 + 验证码登录 |
|
||||
| 5 | `POST /api/v1/auth/refresh` | 无 | 刷新 token |
|
||||
| 6 | `GET /api/v1/auth/me` | Bearer | 获取当前登录用户 |
|
||||
| 7 | `POST /api/v1/auth/logout` | Bearer | 登出(服务端占位) |
|
||||
| 8 | `POST /api/v1/meituan/coupons` | 无 | 券列表 / 搜索 |
|
||||
| 9 | `POST /api/v1/meituan/feed` | 无 | 首页混合推荐流 |
|
||||
| 10 | `POST /api/v1/meituan/referral-link` | 无 | 换取推广链接(点"抢"时调) |
|
||||
|
||||
> ⚠️ 美团三个接口当前**无鉴权**,且 `referral-link` 的 `sid` 允许客户端传值覆盖默认渠道——见各接口"备注"。
|
||||
|
||||
---
|
||||
|
||||
## 复用数据结构
|
||||
|
||||
### TokenPair
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `access_token` | string | 访问令牌,之后每个鉴权请求带 `Authorization: Bearer <它>` |
|
||||
| `refresh_token` | string | 刷新令牌 |
|
||||
| `token_type` | string | 固定 `"Bearer"` |
|
||||
| `expires_in` | int | access 剩余秒数(默认 7200 = 2h) |
|
||||
| `refresh_expires_in` | int | refresh 剩余秒数(默认 2592000 = 30d) |
|
||||
|
||||
### TokenWithUser
|
||||
继承 `TokenPair` 全部字段,额外多一个 `user`(`UserOut`)。登录类接口成功时返回此结构。
|
||||
|
||||
### UserOut
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `id` | int | 用户主键 |
|
||||
| `phone` | string | 手机号 |
|
||||
| `nickname` | string \| null | 昵称(当前无接口可改,恒为 null) |
|
||||
| `avatar_url` | string \| null | 头像(同上) |
|
||||
| `register_channel` | string | 注册渠道:`jverify` / `sms` |
|
||||
| `status` | string | `active` / `disabled` / `deleted` |
|
||||
| `created_at` | datetime | 注册时间 |
|
||||
| `last_login_at` | datetime | 最近登录时间 |
|
||||
|
||||
### CouponCard(券卡片,`coupons` 与 `feed` 的 `items` 元素)
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `product_view_sign` | string | **换链主键**(传给 `referral-link`) |
|
||||
| `platform` | int | `1`=外卖/到家, `2`=到店 |
|
||||
| `biz_line` | int \| null | 到店子类:1到餐 2到综 3酒店 4门票 |
|
||||
| `name` | string | 商品名 |
|
||||
| `head_image_url` | string | 头图 |
|
||||
| `brand_name` | string \| null | 品牌名 |
|
||||
| `brand_logo_url` | string \| null | 品牌 logo |
|
||||
| `sell_price` | string | 现价 |
|
||||
| `original_price` | string | 原价 |
|
||||
| `discount_amount` | string | 优惠额 = 原价 − 现价 |
|
||||
| `commission_rate` | string | 佣金比例,如 `"1.4%"` |
|
||||
| `commission_amount` | string \| null | 预估佣金(元) |
|
||||
| `sale_volume` | string \| null | 销量 |
|
||||
| `poi_name` | string \| null | 最近门店名 |
|
||||
| `distance_text` | string \| null | 格式化距离,如 `"600m"` / `"1.5km"` |
|
||||
| `distance_meters` | float \| null | 原始距离(米) |
|
||||
| `available_poi_num` | int \| null | 可用门店数 |
|
||||
| `coupon_num` | int \| null | 券张数 |
|
||||
| `valid_days` | int \| null | 券有效天数 |
|
||||
| `price_label` | string \| null | 如 `"15天低价"` |
|
||||
| `rank_label` | string \| null | 如 `"2小时北京外卖销量榜第1名"` |
|
||||
| `rating_label` | string \| null | 如 `"4.6分"` |
|
||||
|
||||
---
|
||||
|
||||
## 1. Meta
|
||||
|
||||
### `GET /health`
|
||||
- **鉴权**:无
|
||||
- **入参**:无
|
||||
- **响应** `200`:`{ "status": "ok" }`
|
||||
|
||||
---
|
||||
|
||||
## 2. Auth 组(前缀 `/api/v1/auth`)
|
||||
|
||||
### 2.1 `POST /jverify-login` — 极光一键登录
|
||||
- **鉴权**:无
|
||||
- **入参**:
|
||||
|
||||
| 字段 | 类型 | 必填 | 说明 |
|
||||
|---|---|---|---|
|
||||
| `login_token` | string | ✅(非空) | 客户端极光 `loginAuth` 拿到的 loginToken |
|
||||
| `operator` | string | ❌(默认 `""`) | 运营商标识 CM/CU/CT,仅用于后端日志 |
|
||||
|
||||
- **响应** `200`:`TokenWithUser`(`user.register_channel` 为 `"jverify"`)
|
||||
- **错误**:`502` 极光验证或 RSA 解密失败;`403` 账号被禁用
|
||||
- **说明**:后端拿 `login_token` 调极光 `loginTokenVerify` 验真 → 取回 RSA 加密的手机号 → 用私钥解密 → 注册即登录(手机号不存在则建号)→ 签发 JWT。
|
||||
|
||||
### 2.2 `POST /sms/send` — 发送短信验证码
|
||||
- **鉴权**:无
|
||||
- **入参**:
|
||||
|
||||
| 字段 | 类型 | 必填 | 说明 |
|
||||
|---|---|---|---|
|
||||
| `phone` | string | ✅ | 手机号,正则 `^1\d{10}$` |
|
||||
|
||||
- **响应** `200`:
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `sent` | bool | 是否已发送 |
|
||||
| `mock` | bool | 是否 mock 模式(true 时不真发,任意 6 位通过) |
|
||||
| `cooldown_sec` | int | 多少秒后才能再次发送 |
|
||||
|
||||
- **错误**:`429` 发送过频(默认 60s 冷却内重复发)
|
||||
- **说明**:mock 模式(`SMS_MOCK=true`)下不真发短信,仅记录冷却时间。
|
||||
|
||||
### 2.3 `POST /sms/login` — 手机号 + 验证码登录
|
||||
- **鉴权**:无
|
||||
- **入参**:
|
||||
|
||||
| 字段 | 类型 | 必填 | 说明 |
|
||||
|---|---|---|---|
|
||||
| `phone` | string | ✅ | 手机号 `^1\d{10}$` |
|
||||
| `code` | string | ✅ | 验证码,长度 4–8 |
|
||||
|
||||
- **响应** `200`:`TokenWithUser`(`user.register_channel` 为 `"sms"`)
|
||||
- **错误**:`400` 验证码错误;`403` 账号被禁用
|
||||
- **说明**:mock 模式下任意 6 位数字均通过校验。注册即登录。
|
||||
|
||||
### 2.4 `POST /refresh` — 刷新 token
|
||||
- **鉴权**:无(凭 body 里的 refresh_token)
|
||||
- **入参**:
|
||||
|
||||
| 字段 | 类型 | 必填 | 说明 |
|
||||
|---|---|---|---|
|
||||
| `refresh_token` | string | ✅ | 有效的 refresh token |
|
||||
|
||||
- **响应** `200`:`TokenPair`(**注意:不含 `user` 字段**)
|
||||
- **错误**:`401` refresh token 无效/过期/类型不对,或用户不存在/被禁用
|
||||
- **说明**:服务端校验 refresh token(验签 + 验过期 + 验类型为 refresh)并查库确认用户仍 active,然后签发**全新的** access+refresh 对。客户端在请求收到 401 时由 OkHttp `Authenticator` 自动调用。
|
||||
|
||||
### 2.5 `GET /me` — 获取当前登录用户
|
||||
- **鉴权**:✅ Bearer access_token
|
||||
- **入参**:无(身份取自 Header token)
|
||||
- **响应** `200`:`UserOut`
|
||||
- **错误**:`401` 未带 token / token 无效或过期 / 用户被禁用
|
||||
|
||||
### 2.6 `POST /logout` — 登出
|
||||
- **鉴权**:✅ Bearer access_token
|
||||
- **入参**:无
|
||||
- **响应** `200`:`{ "ok": true }`
|
||||
- **说明**:服务端**无状态、不吊销 token**(占位实现),真正失效靠客户端删除本地 token。后续若加 jti 黑名单可在此写入。
|
||||
|
||||
---
|
||||
|
||||
## 3. 美团 CPS 组(前缀 `/api/v1/meituan`,**全部无鉴权**)
|
||||
|
||||
### 3.1 `POST /coupons` — 券列表 / 搜索
|
||||
- **鉴权**:无
|
||||
- **入参**:
|
||||
|
||||
| 字段 | 类型 | 必填 | 默认 | 说明 |
|
||||
|---|---|---|---|---|
|
||||
| `longitude` | float | ✅ | — | 经度 |
|
||||
| `latitude` | float | ✅ | — | 纬度 |
|
||||
| `platform` | int | ❌ | 1 | 1=外卖/到家, 2=到店 |
|
||||
| `biz_line` | int | ❌ | null | 到店子类:1到餐 2到综 3酒店 4门票 |
|
||||
| `list_topic_id` | int | ❌ | 3 | 榜单:1精选 2今日必推 3爆款筛选 5限时筛选 |
|
||||
| `keyword` | string | ❌ | null | 搜索词(**填了则忽略 `list_topic_id`,走搜索**) |
|
||||
| `sort_field` | int | ❌ | null | 1价格 2销量 6离我最近(搜索时默认 6) |
|
||||
| `search_id` | string | ❌ | null | 翻页 token,首页不填 |
|
||||
| `page` | int | ❌ | 1 | ≥1 |
|
||||
| `page_size` | int | ❌ | 20 | 1–20 |
|
||||
|
||||
- **响应** `200`:`{ items: CouponCard[], has_next: bool, search_id: string|null }`
|
||||
- **错误**:`502` 美团接口失败
|
||||
- **备注**:当前 Android 客户端**未调用**此接口(搜索功能尚未实现),仅后端实现完整。
|
||||
|
||||
### 3.2 `POST /feed` — 首页混合推荐流
|
||||
- **鉴权**:无
|
||||
- **入参**:
|
||||
|
||||
| 字段 | 类型 | 必填 | 默认 | 说明 |
|
||||
|---|---|---|---|---|
|
||||
| `longitude` | float | ✅ | — | 经度 |
|
||||
| `latitude` | float | ✅ | — | 纬度 |
|
||||
| `page` | int | ❌ | 1 | ≥1 |
|
||||
| `page_size` | int | ❌ | 20 | 1–20 |
|
||||
|
||||
- **响应** `200`:`{ items: CouponCard[], has_next: bool, page: int }`
|
||||
- **备注**:后端在 `coupons` 之上封装的"伪推荐"——每页并发拉一次外卖、一次到店(到餐)榜单,按 **2 外卖 + 1 到店** 交叉去重。榜单组合写死 3 页(第1页爆款、第2页今日必推、第3页外卖精选+到店限时),**第 3 页起 `has_next=false`、第 4 页返空**。
|
||||
⚠️ **可观测性盲区**:`feed` 内部对美团调用异常是静默吞掉返回空列表(不报 502、不打日志)。若 `items` 为空但无错误,优先用 `coupons` 接口逼出真实错误(它会以 502 暴露,如"MT_CPS_APP_KEY not configured")。
|
||||
|
||||
### 3.3 `POST /referral-link` — 换取推广链接
|
||||
- **鉴权**:无
|
||||
- **入参**:
|
||||
|
||||
| 字段 | 类型 | 必填 | 默认 | 说明 |
|
||||
|---|---|---|---|---|
|
||||
| `product_view_sign` | string | ✅ | — | 券的换链主键(来自 `CouponCard`) |
|
||||
| `platform` | int | ❌ | 1 | 1=外卖/到家, 2=到店 |
|
||||
| `biz_line` | int | ❌ | null | 到店子类 |
|
||||
| `sid` | string | ❌ | 服务端默认 `sgbjia` | 渠道追踪标识 |
|
||||
| `link_type_list` | int[] | ❌ | `[1, 3]` | 1=H5长链 2=H5短链 3=deeplink |
|
||||
|
||||
- **响应** `200`:
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `link` | string | 默认推广链接(按 data > H5(1) > deeplink(3) > 任意 兜底) |
|
||||
| `link_map` | object | 各类型链接 `{ "linkType": "url" }`,如 `{"1": "<H5>", "3": "<deeplink>"}` |
|
||||
|
||||
- **错误**:`502` 美团接口失败
|
||||
- **备注**:客户端实际优先用 `link_map["3"]`(deeplink)拉起美团 App,失败降级 `link_map["1"]`(H5)。
|
||||
⚠️ **安全**:`sid` 允许客户端传值覆盖服务端默认渠道,理论上他人可借本接口刷自己渠道的分佣;建议服务端锁定 `sid`、忽略客户端传值。
|
||||
|
||||
---
|
||||
|
||||
## 附:鉴权与刷新机制
|
||||
|
||||
- **签发**:登录成功后签发 access(HS256,2h) + refresh(30d),payload 含 `sub`(user_id)、`typ`(access/refresh)、`iat`、`exp`。
|
||||
- **携带**:客户端对需鉴权接口自动加 `Authorization: Bearer <access>`(登录类接口跳过)。
|
||||
- **校验**(`/me`、`/logout`):验签 → 验过期 → 验 `typ=access` → 查库确认用户存在且 `status=active`,任一不过 → 401。
|
||||
- **续期**:access 过期触发 401 → 客户端用 refresh 调 `/refresh` 换新 token 对并重放原请求;refresh 也失效 → 清本地、跳登录。
|
||||
- **无状态**:token 不落库,服务端无法主动吊销(logout 为占位),靠短 access 有效期限制泄露风险。JWT 密钥 `JWT_SECRET_KEY` 必须为高熵随机串(生产严禁用默认值)。
|
||||
+150
-182
@@ -1,69 +1,81 @@
|
||||
# 傻瓜比价 App Server — 后端技术实现
|
||||
# 傻瓜比价 App Server — 后端技术方案
|
||||
|
||||
> 域名:`app-api.shaguabijia.com`(HTTPS,nginx 反代)
|
||||
> 仓库:`shaguabijia-app-server`
|
||||
> 当前版本:v0.1.0(登录模块)
|
||||
> 最后更新:2026-05-23
|
||||
> 接口协议详见同目录 [`API.md`](./API.md)
|
||||
> 最后更新:2026-05-27
|
||||
|
||||
---
|
||||
|
||||
## 1. 本次实施范围
|
||||
## 1. 这个后端是干什么的
|
||||
|
||||
本阶段目标是搭正式 App 后端的**账号与登录**能力,供 Android 正式版(`shaguabijia-app-android`)对接。
|
||||
为正式版 App(`shaguabijia-app-android`,包名 `com.jishisongfu.shaguabijia`)提供两块能力:
|
||||
|
||||
已实现:
|
||||
| 能力 | 说明 |
|
||||
|---|---|
|
||||
| **账号与登录** | 极光一键登录 + 短信验证码登录(mock)→ 签发 JWT |
|
||||
| **美团 CPS 选品** | 透传美团联盟优惠券(外卖/到店)、点击换取推广链接(分佣) |
|
||||
|
||||
| 能力 | 状态 | 说明 |
|
||||
|---|---|---|
|
||||
| 极光一键登录 | ✅ 已联调 | `loginToken` → 极光 REST 验真 → RSA 解密手机号 → 注册/登录 |
|
||||
| 短信验证码登录 | ✅ mock 可用 | 开发阶段任意 6 位通过,便于无短信供应商时联调 |
|
||||
| JWT 双 token | ✅ | access(2h) + refresh(30d) |
|
||||
| 用户表 + ORM | ✅ | SQLAlchemy 2.0 + Alembic |
|
||||
| `/me` 鉴权 | ✅ | Bearer access_token |
|
||||
| 单元测试 | ✅ | health + sms 登录闭环 + refresh + 限流 |
|
||||
|
||||
未做(后续迭代):
|
||||
|
||||
- 真实短信供应商(阿里云/腾讯云)
|
||||
- logout 服务端 token 黑名单(jti)
|
||||
- 昵称/头像修改、注销账号
|
||||
- PostgreSQL 生产切库(当前 SQLite 起步)
|
||||
**没有"比价"实现**——名字叫比价,实质是美团券聚合 + CPS 分佣。无爬虫、无 LLM、无积分/提现/钱包,数据模型仅一张 `user` 表(美团数据实时透传不落库)。
|
||||
|
||||
---
|
||||
|
||||
## 2. 与试验后台的关系
|
||||
|
||||
| 维度 | 试验后台 `shaguabijia-server` | 正式后台 `shaguabijia-app-server` |
|
||||
|---|---|---|
|
||||
| 域名 | `api.shaguabijia.com` | `app-api.shaguabijia.com` |
|
||||
| 数据库 | stdlib sqlite3,手写 SQL | SQLAlchemy 2.0 + Alembic |
|
||||
| 账号体系 | 仅占坑(phone 当 ID) | User 表 + JWT |
|
||||
| 极光验 token | ✅ 有 | ✅ 移植并增强 |
|
||||
| 短信登录 | ❌ | ✅ mock |
|
||||
| 配置 | 硬编码 | pydantic-settings + `.env` |
|
||||
|
||||
**极光一键登录的核心逻辑**(REST 调用、RSA padding 试错顺序)直接参考试验后台 `app/api/auth.py`,
|
||||
等价实现在 `app/core/jiguang.py`。
|
||||
|
||||
试验后台 RSA 私钥部署在服务器 `/opt/shaguabijia-server/secrets/jverify_rsa_private.pem`(不入 git)。
|
||||
正式后台因原私钥不可用,在极光控制台**重新生成 1024-bit RSA 密钥对**并上传公钥。
|
||||
|
||||
---
|
||||
|
||||
## 3. 技术栈
|
||||
## 2. 技术栈
|
||||
|
||||
| 维度 | 选型 | 说明 |
|
||||
|---|---|---|
|
||||
| 语言 | Python 3.11+ | 本地开发用 3.13 |
|
||||
| Web | FastAPI 0.115+ | OpenAPI 自动生成 |
|
||||
| 语言 | Python ≥3.10 | 本地开发用 conda 环境 `price` |
|
||||
| Web | FastAPI 0.115+ | OpenAPI 自动生成(非 prod 开 `/docs`) |
|
||||
| ASGI | uvicorn[standard] | 生产 `--host 127.0.0.1 --port 8770` |
|
||||
| ORM | SQLAlchemy 2.0 | Mapped 新风格 |
|
||||
| 迁移 | Alembic | `render_as_batch` 兼容 SQLite |
|
||||
| DB | SQLite | 生产可改 `DATABASE_URL` 切 PostgreSQL |
|
||||
| Auth | PyJWT | HS256,access + refresh |
|
||||
| 极光 | httpx + cryptography | REST 验 token + RSA 解密 |
|
||||
| ORM | SQLAlchemy 2.0(Mapped 风格) | |
|
||||
| 迁移 | Alembic | |
|
||||
| DB | SQLite 起步 | 改 `DATABASE_URL` 可切 PostgreSQL,无 Redis |
|
||||
| Auth | PyJWT(HS256) | access + refresh |
|
||||
| 极光 | httpx + cryptography | REST 验 token + RSA 解密手机号 |
|
||||
| 美团 | httpx | 自实现 S-Ca 网关签名 |
|
||||
| 配置 | pydantic-settings | `.env` 加载 |
|
||||
| 测试 | pytest + httpx TestClient | 临时文件 SQLite |
|
||||
| 测试 | pytest + httpx TestClient | |
|
||||
|
||||
---
|
||||
|
||||
## 3. 分层架构与目录结构
|
||||
|
||||
标准 FastAPI 分层,一个请求自上而下穿过:**api(薄,收发) → services 级逻辑(目前内联在路由/集成里) → integrations(外部) / repositories(数据) → models / db**。
|
||||
|
||||
```
|
||||
app/
|
||||
├── main.py # FastAPI 入口:注册路由、CORS、/health、lifespan
|
||||
├── api/
|
||||
│ ├── deps.py # 共享依赖:get_current_user(鉴权)、get_db(注入 session)
|
||||
│ └── v1/
|
||||
│ ├── auth.py # 登录 6 个端点
|
||||
│ └── meituan.py # 美团 3 个端点 + feed 拼接逻辑(_interleave / _TOPIC_ROUNDS)
|
||||
├── schemas/ # Pydantic:API 收发的数据契约(与客户端对齐字段看这里)
|
||||
│ ├── auth.py
|
||||
│ └── meituan.py
|
||||
├── integrations/ # 外部服务客户端(2026-05 从 core 拆出)
|
||||
│ ├── jiguang.py # 极光 REST 验 token + RSA 解密(多 padding 试错)
|
||||
│ ├── meituan.py # 美团 CPS 网关签名 + query_coupon / get_referral_link
|
||||
│ └── sms.py # 短信验证码(mock,进程内存冷却表)
|
||||
├── core/ # 基础设施(仅保留)
|
||||
│ ├── config.py # pydantic-settings
|
||||
│ ├── security.py # JWT 签发/校验
|
||||
│ └── logging.py
|
||||
├── repositories/ # 数据访问(2026-05 由 crud 改名)
|
||||
│ └── user.py # get_user_by_id / get_user_by_phone / upsert_user_for_login
|
||||
├── models/user.py # ORM:user 表结构
|
||||
└── db/
|
||||
├── base.py # DeclarativeBase
|
||||
└── session.py # engine + get_db
|
||||
|
||||
alembic/ # 数据库迁移(versions/ 目前仅 init_user_table)
|
||||
deploy/ # systemd(.service) + nginx(.conf)
|
||||
secrets/ # 极光 RSA 私钥(不入 git,仅 .gitkeep 占位)
|
||||
tests/ # pytest(conftest + test_auth + test_health)
|
||||
run.sh # 本地启动脚本
|
||||
```
|
||||
|
||||
> **命名说明**:`api/v1/` 的 `v1` 用于 URL 版本化(移动端无法强制即时升级,需新旧版本并存能力);`integrations` 装外部集成、`repositories` 装数据访问,与 `core`(基础设施)分离。
|
||||
|
||||
---
|
||||
|
||||
@@ -72,179 +84,135 @@
|
||||
### 4.1 极光一键登录(主路径)
|
||||
|
||||
```
|
||||
Android SDK loginAuth
|
||||
→ 客户端拿到 loginToken
|
||||
→ POST /api/v1/auth/jverify-login { login_token, operator }
|
||||
→ 后端 POST 极光 loginTokenVerify (Basic Auth = AppKey:MasterSecret)
|
||||
→ 极光返回 RSA 加密的手机号(base64)
|
||||
→ 后端用私钥解密(PKCS1v15,实测电信 CT 走此 padding)
|
||||
→ upsert User(phone 唯一) → 签 JWT → 返回 TokenWithUser
|
||||
Android SDK loginAuth → 客户端拿到 loginToken
|
||||
→ POST /api/v1/auth/jverify-login { login_token, operator }
|
||||
→ 后端 POST 极光 loginTokenVerify (Basic Auth = AppKey:MasterSecret)
|
||||
→ 极光返回 RSA 公钥加密的手机号(base64)
|
||||
→ 后端用配套私钥解密 → 明文手机号
|
||||
→ upsert_user_for_login(phone 唯一) → 签 JWT → 返回 TokenWithUser
|
||||
```
|
||||
|
||||
**关键配置**(与 Android 端必须一致):
|
||||
**RSA 解密**(`integrations/jiguang.py` 的 `_decrypt_phone`):极光文档未明示 padding,代码按 **OAEP-SHA1 → OAEP-SHA256 → PKCS1v15** 依次试,解出 11 位纯数字手机号即采用(PKCS1v15 对错误密文会"假成功"返回非 UTF-8 垃圾,据此跳过)。
|
||||
|
||||
**关键配置**(须与 Android 端一致):
|
||||
|
||||
| 项 | 值 |
|
||||
|---|---|
|
||||
| 包名 | `com.jishisongfu.shaguabijia` |
|
||||
| 极光 AppKey | `966b451a8d9cfe12d173ea9d` |
|
||||
| RSA 公钥 | 极光控制台「加密公钥」(1024-bit,≤220 字符) |
|
||||
| RSA 私钥 | `secrets/jverify_rsa_private.pem`(不入 git) |
|
||||
| 极光 AppKey | `966b451a8d9cfe12d173ea9d`(`JG_APP_KEY`) |
|
||||
| RSA 公钥 | 极光控制台「加密公钥」(**1024-bit**,极光限制 ≤220 字符) |
|
||||
| RSA 私钥 | `secrets/jverify_rsa_private.pem`(PKCS#8,不入 git,`JG_PRIVATE_KEY_PATH` 指定,懒加载) |
|
||||
|
||||
**RSA 密钥说明**:
|
||||
|
||||
- 密钥对由我方生成(`openssl genrsa 1024`),公钥上传极光控制台
|
||||
- 极光控制台限制公钥长度 ≤220 字符,因此用 **1024-bit** 而非 2048-bit
|
||||
- 私钥路径由 `JG_PRIVATE_KEY_PATH` 指定,懒加载;文件不存在时 `jverify-login` 返回 502
|
||||
> **密钥对配对关系是关键**:极光用控制台上传的公钥加密,后端必须用**配对的私钥**解密。私钥不配对时 `jverify-login` 报 502 `all RSA paddings failed`(密钥不对,非 padding 问题);私钥文件缺失则报 502 `private key not found`。
|
||||
> **2026-05-27 现状**:历史遗留的两套本地密钥(`codes/secrets/jverification/`、`docs/试水版上架材料/`)均**不配对**当前 AppKey 公钥,已重新生成一对 1024-bit/PKCS#8 密钥,公钥需在极光控制台更新。⚠️ 该 AppKey 公钥为全局配置,若占坑版后端仍在用同一 AppKey,换公钥会使其旧私钥失效,需同步部署新私钥。
|
||||
|
||||
### 4.2 短信登录(mock 路径)
|
||||
|
||||
```
|
||||
POST /api/v1/auth/sms/send { phone } → 60s 冷却,不真发短信
|
||||
POST /api/v1/auth/sms/login { phone, code } → 任意 6 位通过(SMS_MOCK=true)
|
||||
→ upsert User → 签 JWT → 返回 TokenWithUser
|
||||
POST /api/v1/auth/sms/send { phone } → 60s 冷却,不真发(SMS_MOCK=true)
|
||||
POST /api/v1/auth/sms/login { phone, code } → 任意 6 位通过 → upsert → 签 JWT
|
||||
```
|
||||
|
||||
### 4.3 Token 刷新
|
||||
短信冷却表存进程内存(`--workers 1` 下够用,多 worker/重启即失效)。
|
||||
|
||||
```
|
||||
POST /api/v1/auth/refresh { refresh_token }
|
||||
→ 校验 refresh token → 签新 access+refresh 对
|
||||
```
|
||||
### 4.3 Token 与刷新
|
||||
|
||||
Android 端通过 OkHttp `Authenticator` 在 401 时自动调用。
|
||||
- access(2h)+ refresh(30d),HS256 自包含,payload 含 `sub`/`typ`/`iat`/`exp`,**无 session 表、无 jti 黑名单**。
|
||||
- `refresh` 校验 token + 查库确认用户 active 后,签发**全新一对**。
|
||||
- 客户端 OkHttp `Authenticator` 在 401 时自动调 `/refresh` 续期重放。
|
||||
- `logout` 为占位(服务端不吊销 token)。
|
||||
|
||||
---
|
||||
|
||||
## 5. 数据模型
|
||||
## 5. 美团 CPS
|
||||
|
||||
### User 表
|
||||
### 5.1 网关签名(`integrations/meituan.py` 的 `_sign` / `_call`)
|
||||
|
||||
类阿里云 S-Ca 网关签名,**stringToSign 只有 4 段**:`METHOD\n + Content-MD5\n + 排序后的 signed_headers + path`,**不含 Accept / Content-Type / Date 行**(加了签名失败)。头:`S-Ca-App`(=appkey)、`S-Ca-Timestamp`、`S-Ca-Signature`、`S-Ca-Signature-Headers`。配置项 `MT_CPS_APP_KEY` / `MT_CPS_APP_SECRET` / `MT_CPS_DEFAULT_SID`(默认 `sgbjia`)。
|
||||
|
||||
> 美团请求字段 `listTopiId`(少个 c)是官方拼写,非笔误。经纬度 `*1_000_000` 取整。
|
||||
|
||||
### 5.2 三个接口
|
||||
|
||||
- `query_coupon`:底层取数,被 `coupons` 路由和 `feed` 路由共用。
|
||||
- `coupons` 路由:对外的搜索/榜单接口,**客户端暂未接入**。
|
||||
- `feed` 路由:首页推荐流,每页并发拉外卖(platform=1)+ 到店(platform=2,到餐)各一次,按 **2 外卖 + 1 到店** 交叉去重(`_interleave`);榜单组合写死 3 页(`_TOPIC_ROUNDS`:爆款 / 今日必推 / 外卖精选+到店限时),第 3 页 `has_next=false`、第 4 页返空。
|
||||
- `referral-link`:换推广链接,客户端取 `link_map["3"]`(deeplink)优先跳美团 App。
|
||||
|
||||
### 5.3 风险点
|
||||
|
||||
- **三接口无鉴权**:任何人可调,消耗你的美团 appkey 能力/配额。
|
||||
- **`sid` 可被客户端覆盖**:他人可借接口刷自己渠道分佣,建议服务端锁定。
|
||||
- **`feed` 静默吞异常**:`_fetch_topic` 对美团错误 `except 返回 []` 且不打日志,导致美团失败时 `feed` 返回"200 + 空 items"无声失败。排查时改用 `coupons`(它以 502 暴露错误)。
|
||||
|
||||
---
|
||||
|
||||
## 6. 数据模型
|
||||
|
||||
仅一张 `user` 表(`models/user.py`):
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| id | INTEGER PK | 自增 |
|
||||
| phone | VARCHAR UNIQUE | 手机号,登录主键 |
|
||||
| register_channel | VARCHAR | `jverify` / `sms` |
|
||||
| nickname | VARCHAR NULL | 预留 |
|
||||
| avatar_url | VARCHAR NULL | 预留 |
|
||||
| status | VARCHAR | `active` / `disabled` |
|
||||
| created_at | DATETIME | 注册时间 |
|
||||
| last_login_at | DATETIME | 最近登录 |
|
||||
| phone | VARCHAR(20) UNIQUE | 登录主键,唯一索引 `ix_user_phone` |
|
||||
| register_channel | VARCHAR(20) | `jverify` / `sms` |
|
||||
| nickname | VARCHAR(64) NULL | 预留,**无接口可写,恒为 null** |
|
||||
| avatar_url | VARCHAR(512) NULL | 同上 |
|
||||
| status | VARCHAR(20) | `active` / `disabled` / `deleted`,仅 active 可登录/鉴权 |
|
||||
| created_at / last_login_at | DATETIME(tz) | |
|
||||
|
||||
`upsert_user_for_login`:phone 存在则更新 `last_login_at`,不存在则注册。
|
||||
`upsert_user_for_login`:phone 存在则更新 `last_login_at`,不存在则注册(注册即登录)。Alembic 实际库里另有框架表 `alembic_version`。
|
||||
|
||||
---
|
||||
|
||||
## 6. API 一览
|
||||
## 7. 配置与部署
|
||||
|
||||
| 方法 | 路径 | 鉴权 | 说明 |
|
||||
|---|---|---|---|
|
||||
| GET | `/health` | 无 | 健康检查 |
|
||||
| POST | `/api/v1/auth/jverify-login` | 无 | 极光一键登录 |
|
||||
| POST | `/api/v1/auth/sms/send` | 无 | 发短信(mock) |
|
||||
| POST | `/api/v1/auth/sms/login` | 无 | 短信登录 |
|
||||
| POST | `/api/v1/auth/refresh` | 无 | 刷新 token |
|
||||
| GET | `/api/v1/auth/me` | Bearer | 当前用户 |
|
||||
| POST | `/api/v1/auth/logout` | Bearer | 登出占位 |
|
||||
配置见 `core/config.py`(pydantic-settings 读 `.env`)。分组:环境、`DATABASE_URL`、JWT、极光(`JG_*`)、短信(`SMS_MOCK` 默认 true)、美团(`MT_CPS_*`)、CORS。
|
||||
|
||||
Swagger UI: `http://localhost:8770/docs`
|
||||
|
||||
---
|
||||
|
||||
## 7. 目录结构
|
||||
|
||||
```
|
||||
app/
|
||||
├── main.py # FastAPI 入口,lifespan,CORS
|
||||
├── core/
|
||||
│ ├── config.py # pydantic-settings
|
||||
│ ├── security.py # JWT 签发/校验
|
||||
│ ├── jiguang.py # 极光 REST + RSA 解密
|
||||
│ └── sms.py # 短信 mock(内存验证码)
|
||||
├── db/
|
||||
│ ├── base.py
|
||||
│ └── session.py # engine + get_db
|
||||
├── models/user.py
|
||||
├── schemas/auth.py
|
||||
├── crud/user.py
|
||||
└── api/
|
||||
├── deps.py # get_current_user
|
||||
└── v1/auth.py # 登录路由
|
||||
|
||||
alembic/ # 数据库迁移
|
||||
deploy/ # systemd + nginx
|
||||
secrets/ # RSA 私钥(不入 git)
|
||||
tests/ # pytest
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 8. 本地联调(真机 + LAN)
|
||||
|
||||
后端监听所有网卡,供同一 WiFi 下的测试机访问:
|
||||
**生产部署**:systemd `shaguabijia-app-server.service`(WorkingDirectory `/opt/shaguabijia-app-server`,`EnvironmentFile=.env`,uvicorn 监听 `127.0.0.1:8770`,`--workers 1`)+ nginx 443 反代 → 8770。**无 Docker**。
|
||||
|
||||
```bash
|
||||
source .venv/bin/activate
|
||||
uvicorn app.main:app --host 0.0.0.0 --port 8770 --reload
|
||||
```
|
||||
|
||||
Android debug 包 `BASE_URL` 指向开发机 LAN IP(配置在 `local.properties`,不入 git):
|
||||
|
||||
```
|
||||
debug.api.host=192.168.x.x
|
||||
debug.api.port=8770
|
||||
```
|
||||
|
||||
真机浏览器访问 `http://192.168.x.x:8770/health` 应返回 `{"status":"ok"}`。
|
||||
|
||||
---
|
||||
|
||||
## 9. 部署要点
|
||||
|
||||
```bash
|
||||
# 代码同步(排除 secrets 和 data)
|
||||
rsync -avz --exclude='.venv' --exclude='data' --exclude='secrets/*.pem' \
|
||||
./ server:/opt/shaguabijia-app-server/
|
||||
|
||||
# 私钥单独 scp(仅首次或轮换时)
|
||||
# 同步代码(排除虚拟环境/数据/私钥)
|
||||
rsync -avz --exclude='.venv' --exclude='__pycache__' --exclude='data' --exclude='secrets/*.pem' ./ server:/opt/shaguabijia-app-server/
|
||||
# 私钥单独 scp(不入 git)
|
||||
scp secrets/jverify_rsa_private.pem server:/opt/shaguabijia-app-server/secrets/
|
||||
|
||||
# 迁移 + 重启
|
||||
ssh server "cd /opt/shaguabijia-app-server && .venv/bin/alembic upgrade head && systemctl restart shaguabijia-app-server"
|
||||
```
|
||||
|
||||
生产 checklist:
|
||||
**生产 checklist(均为上线必查)**:
|
||||
|
||||
- [ ] `JWT_SECRET_KEY` 换成随机长字符串
|
||||
- [ ] `APP_ENV=prod`, `APP_DEBUG=false`
|
||||
- [ ] RSA 私钥权限 `chmod 600`
|
||||
- [ ] nginx SSL 证书有效
|
||||
- [ ] `alembic upgrade head` 已执行
|
||||
- [ ] `JWT_SECRET_KEY` 改为高熵随机串(`python -c "import secrets;print(secrets.token_urlsafe(64))"`)——默认值 `change-me` 可被伪造 token
|
||||
- [ ] `SMS_MOCK=false` 并接真实短信供应商——mock 下任意 6 位码可登录任意手机号
|
||||
- [ ] `MT_CPS_APP_KEY` / `MT_CPS_APP_SECRET` 已填(否则美团接口 502)
|
||||
- [ ] RSA 私钥就位且与极光控制台公钥**配对**,权限 600
|
||||
- [ ] `APP_ENV=prod`、`APP_DEBUG=false`、nginx SSL 有效、`alembic upgrade head` 已执行
|
||||
|
||||
---
|
||||
|
||||
## 10. 已知问题与后续
|
||||
## 8. 本地联调(真机)
|
||||
|
||||
```bash
|
||||
conda activate price # 首次:pip install -e .
|
||||
./run.sh # 校验 .env → alembic 建表 → uvicorn 监听 0.0.0.0:8770
|
||||
```
|
||||
|
||||
真机两种连法(详见前端文档):
|
||||
- **adb reverse**(推荐):`adb reverse tcp:8770 tcp:8770`,前端 `debug.api.host=127.0.0.1`,USB 直连不依赖 WiFi。
|
||||
- **局域网 IP**:前端 `debug.api.host=<开发机 LAN IP>`,手机电脑同 WiFi。
|
||||
|
||||
前端 debug 包对明文 HTTP 整体放行(`src/debug` 的 network_security_config),换 IP 只改 `local.properties`、无需改 xml。
|
||||
|
||||
---
|
||||
|
||||
## 9. 已知问题与后续
|
||||
|
||||
| 项 | 说明 |
|
||||
|---|---|
|
||||
| logout 无服务端失效 | 目前靠客户端清 token;后续可加 jti 黑名单表 |
|
||||
| SMS 为 mock | 上线前需接真实短信供应商并设 `SMS_MOCK=false` |
|
||||
| SQLite 并发 | 生产流量上来后切 PostgreSQL,只改 `DATABASE_URL` |
|
||||
| 极光 RSA 1024-bit | 极光控制台限制所致;仅加密 11 位手机号,可接受 |
|
||||
|
||||
---
|
||||
|
||||
## 11. 联调验证记录(2026-05-23)
|
||||
|
||||
本地 LAN 联调已通过:
|
||||
|
||||
```
|
||||
# 短信登录
|
||||
POST /api/v1/auth/sms/login → 200, user_id=2, phone=177****82
|
||||
|
||||
# 极光一键登录
|
||||
POST /api/v1/auth/jverify-login → 200, operator=CT, token_len=448
|
||||
[JG] decrypted with padding=PKCS1v15
|
||||
jverify_login ok user_id=3, phone=153****91
|
||||
```
|
||||
|
||||
Android 端包名、签名、极光 AppKey 与控制台一致,SDK init 8000,loginAuth 6000。
|
||||
| logout 无服务端失效 | 靠客户端清 token;后续加 jti 黑名单表 |
|
||||
| 美团接口无鉴权 + sid 可覆盖 | 评估加鉴权/锁定 sid(注意首页要求未登录可见) |
|
||||
| feed 静默吞异常 | 建议给 `_fetch_topic` 加日志,避免无声失败 |
|
||||
| SMS 为 mock | 上线接真实供应商 + `SMS_MOCK=false` |
|
||||
| 短信冷却存内存 | 扩 worker 前需迁移到 Redis |
|
||||
| SQLite | 流量上来切 PostgreSQL,只改 `DATABASE_URL` |
|
||||
| 文档可观测性 | API 协议见 `API.md`,以代码为准 |
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
name = "shaguabijia-app-server"
|
||||
version = "0.1.0"
|
||||
description = "Shaguabijia 正式 App 后端 (FastAPI + SQLAlchemy + JWT)"
|
||||
requires-python = ">=3.11"
|
||||
requires-python = ">=3.10"
|
||||
dependencies = [
|
||||
# Web 框架 & ASGI
|
||||
"fastapi>=0.115.0",
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
#!/usr/bin/env bash
|
||||
# 本地开发启动脚本:监听 0.0.0.0(真机局域网 / adb reverse 都能连),改代码自动重启。
|
||||
#
|
||||
# 前置(首次):先激活装好依赖的环境,例如:
|
||||
# conda activate price && pip install -e .
|
||||
# 真机联调流程见前台 local.properties 的 debug.api.host。
|
||||
set -e
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
if [ ! -f .env ]; then
|
||||
echo "❌ 缺 .env:先 cp .env.example .env 并填值(至少 JWT_SECRET_KEY;测美团再填 MT_CPS_*)"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
mkdir -p data # sqlite 文件所在目录
|
||||
alembic upgrade head # 确保表已建(幂等,已是最新则 no-op)
|
||||
|
||||
exec uvicorn app.main:app --host 0.0.0.0 --port 8770 --reload
|
||||
Reference in New Issue
Block a user