From 8fe58f4a4251de0aa25f007f3919b6891f798376 Mon Sep 17 00:00:00 2001 From: no_gen_mu Date: Mon, 25 May 2026 19:46:14 +0800 Subject: [PATCH 1/5] feat(coupon): add /api/v1/coupon/step proxy to pricebot - new POST /api/v1/coupon/step, JWT-authenticated, async httpx forwards body to pricebot - new PRICEBOT_BASE_URL / PRICEBOT_REQUEST_TIMEOUT_SEC settings (default localhost:8000) - error handling: pricebot unreachable / 5xx -> 502 with friendly message - tests: auth, passthrough, 5xx, unreachable, invalid json (5 cases, all pass) Co-Authored-By: Claude Opus 4.7 (1M context) --- .env.example | 7 ++ app/api/v1/coupon.py | 72 +++++++++++++++++++ app/core/config.py | 6 ++ app/main.py | 2 + tests/test_coupon_proxy.py | 143 +++++++++++++++++++++++++++++++++++++ 5 files changed, 230 insertions(+) create mode 100644 app/api/v1/coupon.py create mode 100644 tests/test_coupon_proxy.py diff --git a/.env.example b/.env.example index 83a6cf8..2ac45d7 100644 --- a/.env.example +++ b/.env.example @@ -34,6 +34,13 @@ SMS_MOCK=true SMS_CODE_TTL_SEC=300 SMS_SEND_INTERVAL_SEC=60 +# ===== Pricebot 上游 (领券业务透传目标) ===== +# 客户端调本服务的 /api/v1/coupon/step,我们透传到 pricebot-backend 的 /api/coupon/step。 +# 本地开发用 localhost:8000。生产部署改成内网地址(如 http://pricebot.internal:8000)。 +PRICEBOT_BASE_URL=http://localhost:8000 +# 领券单帧最多 wait 6s,加网络往返,30s 兜底 +PRICEBOT_REQUEST_TIMEOUT_SEC=30 + # ===== CORS ===== # 逗号分隔,生产留空(只让 app 调,不开放 web)。本地开发可加 http://localhost:5173 之类 CORS_ALLOW_ORIGINS= diff --git a/app/api/v1/coupon.py b/app/api/v1/coupon.py new file mode 100644 index 0000000..f91327f --- /dev/null +++ b/app/api/v1/coupon.py @@ -0,0 +1,72 @@ +"""领券业务透传端点。 + +把客户端的 POST /api/v1/coupon/step 请求原样转发给 pricebot-backend +的 /api/coupon/step,只在外层加 JWT 鉴权。 + +pricebot 协议文档: + pricebot-backend/docs/projects/领券-客户端对接协议.md +""" +from __future__ import annotations + +import logging +from typing import Any + +import httpx +from fastapi import APIRouter, HTTPException, Request, status + +from app.api.deps import CurrentUser +from app.core.config import settings + +logger = logging.getLogger("shagua.coupon") + +router = APIRouter(prefix="/api/v1/coupon", tags=["coupon"]) + + +@router.post("/step", summary="领券任务步进 (透传到 pricebot)") +async def coupon_step( + request: Request, + user: CurrentUser, +) -> dict[str, Any]: + """把请求体原样转发给 pricebot-backend 的 /api/coupon/step。 + + - 鉴权: Bearer access_token (get_current_user 隐式校验) + - 透传: 不做 schema 校验,pricebot 自己校验 + - 失败: 网络不可达 / pricebot 5xx → 502 + 友好 message + """ + try: + body = await request.json() + except Exception as e: + raise HTTPException(status_code=400, detail=f"invalid json body: {e}") from e + + url = f"{settings.PRICEBOT_BASE_URL.rstrip('/')}/api/coupon/step" + timeout = settings.PRICEBOT_REQUEST_TIMEOUT_SEC + + logger.info( + "coupon_step user_id=%d trace_id=%s step=%s", + user.id, + body.get("trace_id"), + body.get("step"), + ) + + try: + async with httpx.AsyncClient(timeout=timeout) as client: + resp = await client.post(url, json=body) + except httpx.RequestError as e: + logger.error("[pricebot] request failed: %s", e) + raise HTTPException( + status_code=status.HTTP_502_BAD_GATEWAY, + detail=f"pricebot upstream unreachable: {e}", + ) from e + + if resp.status_code >= 500: + logger.error( + "[pricebot] 5xx status=%d body=%s", + resp.status_code, + resp.text[:500], + ) + raise HTTPException( + status_code=status.HTTP_502_BAD_GATEWAY, + detail=f"pricebot upstream returned {resp.status_code}", + ) + + return resp.json() diff --git a/app/core/config.py b/app/core/config.py index 0cd99e4..e93710b 100644 --- a/app/core/config.py +++ b/app/core/config.py @@ -46,6 +46,12 @@ class Settings(BaseSettings): SMS_CODE_TTL_SEC: int = 300 SMS_SEND_INTERVAL_SEC: int = 60 + # ===== Pricebot 上游 (领券业务透传目标) ===== + # pricebot-backend 默认跑在 8000。/api/v1/coupon/step 会透传到这里的 /api/coupon/step + PRICEBOT_BASE_URL: str = "http://localhost:8000" + # 领券一帧最多 wait 6s,加网络往返,timeout 给 30s 比较稳 + PRICEBOT_REQUEST_TIMEOUT_SEC: int = 30 + # ===== CORS ===== CORS_ALLOW_ORIGINS: str = "" diff --git a/app/main.py b/app/main.py index 2a6c7ff..5fd793a 100644 --- a/app/main.py +++ b/app/main.py @@ -12,6 +12,7 @@ from fastapi import FastAPI 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.core.config import settings from app.core.logging import setup_logging @@ -57,3 +58,4 @@ def health() -> dict[str, str]: app.include_router(auth_router) +app.include_router(coupon_router) diff --git a/tests/test_coupon_proxy.py b/tests/test_coupon_proxy.py new file mode 100644 index 0000000..41033e9 --- /dev/null +++ b/tests/test_coupon_proxy.py @@ -0,0 +1,143 @@ +"""/api/v1/coupon/step 透传端点测试。 + +mock 掉对 pricebot 的 httpx 调用,验证: + 1. 无 token → 401 + 2. 带 token + pricebot 200 → 响应原样透传,请求 body 原样转发 + 3. pricebot 5xx → 502 + 4. pricebot 网络错误 → 502 +""" +from __future__ import annotations + +import time +from unittest.mock import MagicMock, patch + +import httpx +import pytest + + +def _stub_screen_state() -> dict: + """最简的 screen_state(领券业务用,跟外卖/电商同结构)。""" + return { + "screen": {"width": 1080, "height": 2340, "density": 3.0}, + "foreground": {"package": "x", "activity": ""}, + "windows": [], + } + + +def _stub_request_body() -> dict: + return { + "device_id": "test-device", + "trace_id": "test-trace-1", + "step": 0, + "screen_state": _stub_screen_state(), + } + + +@pytest.fixture() +def access_token(client) -> str: + """sms 登录拿一个 access_token。每次新 phone 避免冷却 429。""" + phone = f"139{int(time.time() * 1000) % 100000000:08d}" + r = client.post("/api/v1/auth/sms/send", json={"phone": phone}) + assert r.status_code == 200, r.text + r = client.post("/api/v1/auth/sms/login", json={"phone": phone, "code": "123456"}) + assert r.status_code == 200, r.text + return r.json()["access_token"] + + +def test_coupon_step_requires_auth(client) -> None: + """无 token → 401(get_current_user 拦下)。""" + r = client.post("/api/v1/coupon/step", json=_stub_request_body()) + assert r.status_code == 401 + + +def test_coupon_step_passes_body_through(client, access_token) -> None: + """带 token + pricebot 200 → 响应原样透传,请求 body 原样转发到 /api/coupon/step。""" + fake_pricebot_resp = { + "success": True, + "action": { + "command": "launch", + "params": {"app": "美团", "deeplink": "imeituan://test"}, + }, + "continue": True, + "status": { + "platform": "coupon", + "progress": { + "current": 1, + "total": 2, + "current_coupon_id": "mt_banjia", + "current_coupon_name": "美团半价周末", + }, + }, + } + + captured: dict = {} + + async def fake_post(self, url, json=None, **kw): + captured["url"] = url + captured["json"] = json + mock_resp = MagicMock() + mock_resp.status_code = 200 + mock_resp.json = lambda: fake_pricebot_resp + return mock_resp + + with patch.object(httpx.AsyncClient, "post", fake_post): + r = client.post( + "/api/v1/coupon/step", + headers={"Authorization": f"Bearer {access_token}"}, + json=_stub_request_body(), + ) + + assert r.status_code == 200, r.text + assert r.json() == fake_pricebot_resp + # 验证请求被原样转发(body 不动 + URL 指向 pricebot) + assert captured["json"] == _stub_request_body() + assert captured["url"].endswith("/api/coupon/step") + + +def test_coupon_step_pricebot_5xx_returns_502(client, access_token) -> None: + """pricebot 返 503 → 我们返 502。""" + async def fake_post(self, url, json=None, **kw): + mock_resp = MagicMock() + mock_resp.status_code = 503 + mock_resp.text = "service unavailable" + return mock_resp + + with patch.object(httpx.AsyncClient, "post", fake_post): + r = client.post( + "/api/v1/coupon/step", + headers={"Authorization": f"Bearer {access_token}"}, + json=_stub_request_body(), + ) + + assert r.status_code == 502 + assert "pricebot upstream returned 503" in r.json()["detail"] + + +def test_coupon_step_pricebot_unreachable_returns_502(client, access_token) -> None: + """pricebot 网络不可达 → 502。""" + async def fake_post(self, url, json=None, **kw): + raise httpx.ConnectError("connection refused") + + with patch.object(httpx.AsyncClient, "post", fake_post): + r = client.post( + "/api/v1/coupon/step", + headers={"Authorization": f"Bearer {access_token}"}, + json=_stub_request_body(), + ) + + assert r.status_code == 502 + assert "pricebot upstream unreachable" in r.json()["detail"] + + +def test_coupon_step_invalid_json_body(client, access_token) -> None: + """非 JSON body → 400(在转发前就拒绝)。""" + r = client.post( + "/api/v1/coupon/step", + headers={ + "Authorization": f"Bearer {access_token}", + "Content-Type": "application/json", + }, + content=b"not-json", + ) + assert r.status_code == 400 + assert "invalid json body" in r.json()["detail"] From a2263b48a06ff8b0b9b0c6bc3e9f591aaee5b8a6 Mon Sep 17 00:00:00 2001 From: marco Date: Wed, 27 May 2026 12:07:54 +0800 Subject: [PATCH 2/5] =?UTF-8?q?docs:=20API=20=E6=96=87=E6=A1=A3=E6=8B=86?= =?UTF-8?q?=E5=88=86=E4=B8=BA=20docs/api/(=E7=B4=A2=E5=BC=95+=E4=B8=80?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E4=B8=80=E6=96=87=E4=BB=B6),=20=E8=A1=A5?= =?UTF-8?q?=E5=85=A8=E9=81=97=E6=BC=8F=E7=9A=84=20coupon/step?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 单文件 docs/API.md 拆成 docs/api/: README.md(传送门索引: 11 接口总览表 + 通用约定 + 复用结构) + 11 个一接口一文件, 便于接口增多后维护 - 补全此前 API.md 与技术文档均遗漏的核心接口 coupon-step.md (一键领券透传 pricebot-backend, 唯一需 JWT 鉴权的业务接口) - 更新 后端技术实现.md: 业务补"领券透传"块、目录补 coupon.py、新增 coupon/step 节、 配置补 PRICEBOT_*、接口索引改指向 docs/api/ Co-Authored-By: Claude Opus 4.7 (1M context) --- docs/API.md | 248 ------------------------------ docs/api/README.md | 105 +++++++++++++ docs/api/auth-jverify-login.md | 20 +++ docs/api/auth-logout.md | 15 ++ docs/api/auth-me.md | 15 ++ docs/api/auth-refresh.md | 18 +++ docs/api/auth-sms-login.md | 20 +++ docs/api/auth-sms-send.md | 24 +++ docs/api/coupon-step.md | 22 +++ docs/api/health.md | 15 ++ docs/api/meituan-coupons.md | 27 ++++ docs/api/meituan-feed.md | 23 +++ docs/api/meituan-referral-link.md | 29 ++++ docs/后端技术实现.md | 59 ++++--- 14 files changed, 373 insertions(+), 267 deletions(-) delete mode 100644 docs/API.md create mode 100644 docs/api/README.md create mode 100644 docs/api/auth-jverify-login.md create mode 100644 docs/api/auth-logout.md create mode 100644 docs/api/auth-me.md create mode 100644 docs/api/auth-refresh.md create mode 100644 docs/api/auth-sms-login.md create mode 100644 docs/api/auth-sms-send.md create mode 100644 docs/api/coupon-step.md create mode 100644 docs/api/health.md create mode 100644 docs/api/meituan-coupons.md create mode 100644 docs/api/meituan-feed.md create mode 100644 docs/api/meituan-referral-link.md diff --git a/docs/API.md b/docs/API.md deleted file mode 100644 index 2719d98..0000000 --- a/docs/API.md +++ /dev/null @@ -1,248 +0,0 @@ -# 傻瓜比价 App 后端 — API 接口文档 - -> Base URL:生产 `https://app-api.shaguabijia.com`;本地联调 `http://<开发机>:8770` -> 协议:HTTP / JSON,请求与响应体均 `application/json`,字段统一 **snake_case** -> 鉴权:需鉴权的接口在请求头带 `Authorization: Bearer ` -> 最后更新: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": "
", "3": ""}` | - -- **错误**:`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 `(登录类接口跳过)。 -- **校验**(`/me`、`/logout`):验签 → 验过期 → 验 `typ=access` → 查库确认用户存在且 `status=active`,任一不过 → 401。 -- **续期**:access 过期触发 401 → 客户端用 refresh 调 `/refresh` 换新 token 对并重放原请求;refresh 也失效 → 清本地、跳登录。 -- **无状态**:token 不落库,服务端无法主动吊销(logout 为占位),靠短 access 有效期限制泄露风险。JWT 密钥 `JWT_SECRET_KEY` 必须为高熵随机串(生产严禁用默认值)。 diff --git a/docs/api/README.md b/docs/api/README.md new file mode 100644 index 0000000..89556a2 --- /dev/null +++ b/docs/api/README.md @@ -0,0 +1,105 @@ +# 傻瓜比价 App 后端 — API 接口文档(索引) + +> Base URL:生产 `https://app-api.shaguabijia.com`;本地联调 `http://<开发机>:8770` +> 协议:HTTP / JSON,请求与响应体均 `application/json`,字段统一 **snake_case** +> 鉴权:需鉴权的接口在请求头带 `Authorization: Bearer ` +> 最后更新:2026-05-27 + +--- + +## 接口总览 + +| # | 方法 + 路径 | 鉴权 | 详情 | +|---|---|---|---| +| 1 | `GET /health` | 无 | [详情](./health.md) | +| 2 | `POST /api/v1/auth/jverify-login` | 无 | [详情](./auth-jverify-login.md) | +| 3 | `POST /api/v1/auth/sms/send` | 无 | [详情](./auth-sms-send.md) | +| 4 | `POST /api/v1/auth/sms/login` | 无 | [详情](./auth-sms-login.md) | +| 5 | `POST /api/v1/auth/refresh` | 无 | [详情](./auth-refresh.md) | +| 6 | `GET /api/v1/auth/me` | Bearer | [详情](./auth-me.md) | +| 7 | `POST /api/v1/auth/logout` | Bearer | [详情](./auth-logout.md) | +| 8 | `POST /api/v1/coupon/step` | Bearer | [详情](./coupon-step.md) | +| 9 | `POST /api/v1/meituan/coupons` | 无 | [详情](./meituan-coupons.md) | +| 10 | `POST /api/v1/meituan/feed` | 无 | [详情](./meituan-feed.md) | +| 11 | `POST /api/v1/meituan/referral-link` | 无 | [详情](./meituan-referral-link.md) | + +> ⚠️ 美团三个接口当前**无鉴权**,且 `referral-link` 的 `sid` 允许客户端传值覆盖默认渠道——见各接口"备注"。 +> `coupon/step` 是后端**唯一需要 JWT 鉴权的业务接口**。 + +--- + +## 通用约定 + +- **时间格式**: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`;生产环境关闭。 + +--- + +## 复用数据结构 + +### 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分"` | + +--- + +## 附:鉴权与刷新机制 + +- **签发**:登录成功后签发 access(HS256,2h) + refresh(30d),payload 含 `sub`(user_id)、`typ`(access/refresh)、`iat`、`exp`。 +- **携带**:客户端对需鉴权接口自动加 `Authorization: Bearer `(登录类接口跳过)。 +- **校验**(`/me`、`/logout`):验签 → 验过期 → 验 `typ=access` → 查库确认用户存在且 `status=active`,任一不过 → 401。 +- **续期**:access 过期触发 401 → 客户端用 refresh 调 `/refresh` 换新 token 对并重放原请求;refresh 也失效 → 清本地、跳登录。 +- **无状态**:token 不落库,服务端无法主动吊销(logout 为占位),靠短 access 有效期限制泄露风险。JWT 密钥 `JWT_SECRET_KEY` 必须为高熵随机串(生产严禁用默认值)。 diff --git a/docs/api/auth-jverify-login.md b/docs/api/auth-jverify-login.md new file mode 100644 index 0000000..5c06120 --- /dev/null +++ b/docs/api/auth-jverify-login.md @@ -0,0 +1,20 @@ +# POST /api/v1/auth/jverify-login — 极光一键登录 + +> 所属:Auth 组(前缀 `/api/v1/auth`) | 鉴权:无 | [← 返回 API 索引](./README.md) + +## 入参 + +| 字段 | 类型 | 必填 | 说明 | +|---|---|---|---| +| `login_token` | string | ✅(非空) | 客户端极光 `loginAuth` 拿到的 loginToken | +| `operator` | string | ❌(默认 `""`) | 运营商标识 CM/CU/CT,仅用于后端日志 | + +## 出参 +响应 `200`:`TokenWithUser`(`user.register_channel` 为 `"jverify"`)。结构见 [API 索引](./README.md#复用数据结构)。 + +## 错误码 +- `502` 极光验证或 RSA 解密失败 +- `403` 账号被禁用 + +## 说明 +后端拿 `login_token` 调极光 `loginTokenVerify` 验真 → 取回 RSA 加密的手机号 → 用私钥解密 → 注册即登录(手机号不存在则建号)→ 签发 JWT。 diff --git a/docs/api/auth-logout.md b/docs/api/auth-logout.md new file mode 100644 index 0000000..041c0f6 --- /dev/null +++ b/docs/api/auth-logout.md @@ -0,0 +1,15 @@ +# POST /api/v1/auth/logout — 登出 + +> 所属:Auth 组(前缀 `/api/v1/auth`) | 鉴权:Bearer access_token | [← 返回 API 索引](./README.md) + +## 入参 +无 + +## 出参 +响应 `200`:`{ "ok": true }` + +## 错误码 +无 + +## 说明 +服务端**无状态、不吊销 token**(占位实现),真正失效靠客户端删除本地 token。后续若加 jti 黑名单可在此写入。 diff --git a/docs/api/auth-me.md b/docs/api/auth-me.md new file mode 100644 index 0000000..01eae87 --- /dev/null +++ b/docs/api/auth-me.md @@ -0,0 +1,15 @@ +# GET /api/v1/auth/me — 获取当前登录用户 + +> 所属:Auth 组(前缀 `/api/v1/auth`) | 鉴权:Bearer access_token | [← 返回 API 索引](./README.md) + +## 入参 +无(身份取自 Header token) + +## 出参 +响应 `200`:`UserOut`。结构见 [API 索引](./README.md#复用数据结构)。 + +## 错误码 +- `401` 未带 token / token 无效或过期 / 用户被禁用 + +## 说明 +无 diff --git a/docs/api/auth-refresh.md b/docs/api/auth-refresh.md new file mode 100644 index 0000000..c2860df --- /dev/null +++ b/docs/api/auth-refresh.md @@ -0,0 +1,18 @@ +# POST /api/v1/auth/refresh — 刷新 token + +> 所属:Auth 组(前缀 `/api/v1/auth`) | 鉴权:无(凭 body 里的 refresh_token) | [← 返回 API 索引](./README.md) + +## 入参 + +| 字段 | 类型 | 必填 | 说明 | +|---|---|---|---| +| `refresh_token` | string | ✅ | 有效的 refresh token | + +## 出参 +响应 `200`:`TokenPair`(**注意:不含 `user` 字段**)。结构见 [API 索引](./README.md#复用数据结构)。 + +## 错误码 +- `401` refresh token 无效/过期/类型不对,或用户不存在/被禁用 + +## 说明 +服务端校验 refresh token(验签 + 验过期 + 验类型为 refresh)并查库确认用户仍 active,然后签发**全新的** access+refresh 对。客户端在请求收到 401 时由 OkHttp `Authenticator` 自动调用。 diff --git a/docs/api/auth-sms-login.md b/docs/api/auth-sms-login.md new file mode 100644 index 0000000..56d7637 --- /dev/null +++ b/docs/api/auth-sms-login.md @@ -0,0 +1,20 @@ +# POST /api/v1/auth/sms/login — 手机号 + 验证码登录 + +> 所属:Auth 组(前缀 `/api/v1/auth`) | 鉴权:无 | [← 返回 API 索引](./README.md) + +## 入参 + +| 字段 | 类型 | 必填 | 说明 | +|---|---|---|---| +| `phone` | string | ✅ | 手机号 `^1\d{10}$` | +| `code` | string | ✅ | 验证码,长度 4–8 | + +## 出参 +响应 `200`:`TokenWithUser`(`user.register_channel` 为 `"sms"`)。结构见 [API 索引](./README.md#复用数据结构)。 + +## 错误码 +- `400` 验证码错误 +- `403` 账号被禁用 + +## 说明 +mock 模式下任意 6 位数字均通过校验。注册即登录。 diff --git a/docs/api/auth-sms-send.md b/docs/api/auth-sms-send.md new file mode 100644 index 0000000..6d00de8 --- /dev/null +++ b/docs/api/auth-sms-send.md @@ -0,0 +1,24 @@ +# POST /api/v1/auth/sms/send — 发送短信验证码 + +> 所属:Auth 组(前缀 `/api/v1/auth`) | 鉴权:无 | [← 返回 API 索引](./README.md) + +## 入参 + +| 字段 | 类型 | 必填 | 说明 | +|---|---|---|---| +| `phone` | string | ✅ | 手机号,正则 `^1\d{10}$` | + +## 出参 +响应 `200`: + +| 字段 | 类型 | 说明 | +|---|---|---| +| `sent` | bool | 是否已发送 | +| `mock` | bool | 是否 mock 模式(true 时不真发,任意 6 位通过) | +| `cooldown_sec` | int | 多少秒后才能再次发送 | + +## 错误码 +- `429` 发送过频(默认 60s 冷却内重复发) + +## 说明 +mock 模式(`SMS_MOCK=true`)下不真发短信,仅记录冷却时间。 diff --git a/docs/api/coupon-step.md b/docs/api/coupon-step.md new file mode 100644 index 0000000..aa21345 --- /dev/null +++ b/docs/api/coupon-step.md @@ -0,0 +1,22 @@ +# POST /api/v1/coupon/step — 一键领券任务步进(透传到 pricebot) + +> 所属:Coupon 组(前缀 `/api/v1/coupon`) | 鉴权:Bearer access_token | [← 返回 API 索引](./README.md) + +## 入参 +任意 JSON body,**不做 schema 校验**,原样透传给上游。后端仅从中读 `trace_id`、`step` 用于日志。 + +## 出参 +pricebot-backend 的响应**原样返回**(JSON object)。 + +## 错误码 +- `400` body 不是合法 JSON +- `502` pricebot 上游不可达(网络错误)或返回 5xx + +## 说明 +本服务只加一层 JWT 鉴权,把请求体原样转发到 `PRICEBOT_BASE_URL` 的 `/api/coupon/step`(async httpx)。真正的领券逻辑在 **pricebot-backend(另一个 repo)**,本接口是"鉴权壳 + 透传"。是产品"一键领券"的接入点,前端目前尚未对接。 + +这是后端**唯一需要 JWT 鉴权的业务接口**。 + +**相关配置**: +- `PRICEBOT_BASE_URL`(默认 `http://localhost:8000`) +- `PRICEBOT_REQUEST_TIMEOUT_SEC`(默认 30s,因领券单帧最多 wait 6s) diff --git a/docs/api/health.md b/docs/api/health.md new file mode 100644 index 0000000..26d4e61 --- /dev/null +++ b/docs/api/health.md @@ -0,0 +1,15 @@ +# GET /health — 健康检查 + +> 所属:Meta | 鉴权:无 | [← 返回 API 索引](./README.md) + +## 入参 +无 + +## 出参 +响应 `200`:`{ "status": "ok" }` + +## 错误码 +无 + +## 说明 +无 diff --git a/docs/api/meituan-coupons.md b/docs/api/meituan-coupons.md new file mode 100644 index 0000000..baf8df2 --- /dev/null +++ b/docs/api/meituan-coupons.md @@ -0,0 +1,27 @@ +# POST /api/v1/meituan/coupons — 券列表 / 搜索 + +> 所属:美团 CPS 组(前缀 `/api/v1/meituan`,**全部无鉴权**) | 鉴权:无 | [← 返回 API 索引](./README.md) + +## 入参 + +| 字段 | 类型 | 必填 | 默认 | 说明 | +|---|---|---|---|---| +| `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 }`。`CouponCard` 结构见 [API 索引](./README.md#复用数据结构)。 + +## 错误码 +- `502` 美团接口失败 + +## 说明 +当前 Android 客户端**未调用**此接口(搜索功能尚未实现),仅后端实现完整。 diff --git a/docs/api/meituan-feed.md b/docs/api/meituan-feed.md new file mode 100644 index 0000000..41959a1 --- /dev/null +++ b/docs/api/meituan-feed.md @@ -0,0 +1,23 @@ +# POST /api/v1/meituan/feed — 首页混合推荐流 + +> 所属:美团 CPS 组(前缀 `/api/v1/meituan`,**全部无鉴权**) | 鉴权:无 | [← 返回 API 索引](./README.md) + +## 入参 + +| 字段 | 类型 | 必填 | 默认 | 说明 | +|---|---|---|---|---| +| `longitude` | float | ✅ | — | 经度 | +| `latitude` | float | ✅ | — | 纬度 | +| `page` | int | ❌ | 1 | ≥1 | +| `page_size` | int | ❌ | 20 | 1–20 | + +## 出参 +响应 `200`:`{ items: CouponCard[], has_next: bool, page: int }`。`CouponCard` 结构见 [API 索引](./README.md#复用数据结构)。 + +## 错误码 +无(见"说明"中的可观测性盲区) + +## 说明 +后端在 `coupons` 之上封装的"伪推荐"——每页并发拉一次外卖、一次到店(到餐)榜单,按 **2 外卖 + 1 到店** 交叉去重。榜单组合写死 3 页(第1页爆款、第2页今日必推、第3页外卖精选+到店限时),**第 3 页起 `has_next=false`、第 4 页返空**。 + +⚠️ **可观测性盲区**:`feed` 内部对美团调用异常是静默吞掉返回空列表(不报 502、不打日志)。若 `items` 为空但无错误,优先用 `coupons` 接口逼出真实错误(它会以 502 暴露,如"MT_CPS_APP_KEY not configured")。 diff --git a/docs/api/meituan-referral-link.md b/docs/api/meituan-referral-link.md new file mode 100644 index 0000000..5cce9a5 --- /dev/null +++ b/docs/api/meituan-referral-link.md @@ -0,0 +1,29 @@ +# POST /api/v1/meituan/referral-link — 换取推广链接 + +> 所属:美团 CPS 组(前缀 `/api/v1/meituan`,**全部无鉴权**) | 鉴权:无 | [← 返回 API 索引](./README.md) + +## 入参 + +| 字段 | 类型 | 必填 | 默认 | 说明 | +|---|---|---|---|---| +| `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": "
", "3": ""}` | + +## 错误码 +- `502` 美团接口失败 + +## 说明 +客户端实际优先用 `link_map["3"]`(deeplink)拉起美团 App,失败降级 `link_map["1"]`(H5)。 + +⚠️ **安全**:`sid` 允许客户端传值覆盖服务端默认渠道,理论上他人可借本接口刷自己渠道的分佣;建议服务端锁定 `sid`、忽略客户端传值。 diff --git a/docs/后端技术实现.md b/docs/后端技术实现.md index 16b0944..84bf3cb 100644 --- a/docs/后端技术实现.md +++ b/docs/后端技术实现.md @@ -2,21 +2,22 @@ > 域名:`app-api.shaguabijia.com`(HTTPS,nginx 反代) > 仓库:`shaguabijia-app-server` -> 接口协议详见同目录 [`API.md`](./API.md) +> 接口协议详见 [`docs/api/`](./api/)(索引 + 一接口一文件) > 最后更新:2026-05-27 --- ## 1. 这个后端是干什么的 -为正式版 App(`shaguabijia-app-android`,包名 `com.jishisongfu.shaguabijia`)提供两块能力: +为正式版 App(`shaguabijia-app-android`,包名 `com.jishisongfu.shaguabijia`)提供三块能力: | 能力 | 说明 | |---|---| | **账号与登录** | 极光一键登录 + 短信验证码登录(mock)→ 签发 JWT | | **美团 CPS 选品** | 透传美团联盟优惠券(外卖/到店)、点击换取推广链接(分佣) | +| **领券透传** | `/coupon/step` 加 JWT 鉴权后转发到 pricebot-backend(一键领券核心,前端待接入) | -**没有"比价"实现**——名字叫比价,实质是美团券聚合 + CPS 分佣。无爬虫、无 LLM、无积分/提现/钱包,数据模型仅一张 `user` 表(美团数据实时透传不落库)。 +**本服务自身没有"比价"实现**——名字叫比价,实质是:登录态 + 美团券聚合分佣 + 给真正的领券/比价核心(pricebot-backend,另一个 repo)做"鉴权 + 透传壳"。无爬虫、无 LLM、无积分/提现/钱包,数据模型仅一张 `user` 表(美团数据与领券请求均实时透传不落库)。 --- @@ -32,7 +33,7 @@ | DB | SQLite 起步 | 改 `DATABASE_URL` 可切 PostgreSQL,无 Redis | | Auth | PyJWT(HS256) | access + refresh | | 极光 | httpx + cryptography | REST 验 token + RSA 解密手机号 | -| 美团 | httpx | 自实现 S-Ca 网关签名 | +| 美团 / pricebot | httpx(含 async) | 美团 S-Ca 网关签名;领券 async 透传 | | 配置 | pydantic-settings | `.env` 加载 | | 测试 | pytest + httpx TestClient | | @@ -40,15 +41,16 @@ ## 3. 分层架构与目录结构 -标准 FastAPI 分层,一个请求自上而下穿过:**api(薄,收发) → services 级逻辑(目前内联在路由/集成里) → integrations(外部) / repositories(数据) → models / db**。 +标准 FastAPI 分层,一个请求自上而下穿过:**api(薄,收发) → integrations(外部) / repositories(数据) → models / db**。 ``` app/ -├── main.py # FastAPI 入口:注册路由、CORS、/health、lifespan +├── main.py # FastAPI 入口:注册 3 个 router、CORS、/health、lifespan ├── api/ │ ├── deps.py # 共享依赖:get_current_user(鉴权)、get_db(注入 session) │ └── v1/ │ ├── auth.py # 登录 6 个端点 +│ ├── coupon.py # 领券透传 /coupon/step(转发 pricebot,唯一需鉴权的业务接口) │ └── meituan.py # 美团 3 个端点 + feed 拼接逻辑(_interleave / _TOPIC_ROUNDS) ├── schemas/ # Pydantic:API 收发的数据契约(与客户端对齐字段看这里) │ ├── auth.py @@ -73,9 +75,10 @@ deploy/ # systemd(.service) + nginx(.conf) secrets/ # 极光 RSA 私钥(不入 git,仅 .gitkeep 占位) tests/ # pytest(conftest + test_auth + test_health) run.sh # 本地启动脚本 +docs/api/ # API 接口文档(索引 README + 一接口一文件) ``` -> **命名说明**:`api/v1/` 的 `v1` 用于 URL 版本化(移动端无法强制即时升级,需新旧版本并存能力);`integrations` 装外部集成、`repositories` 装数据访问,与 `core`(基础设施)分离。 +> **命名说明**:`api/v1/` 的 `v1` 用于 URL 版本化(移动端无法强制即时升级,需新旧版本并存能力);`integrations` 装外部集成、`repositories` 装数据访问,与 `core`(基础设施)分离。`coupon.py` 是领券透传,勿与 `meituan.py` 里的 `coupons`(券列表)混淆。 --- @@ -104,7 +107,7 @@ Android SDK loginAuth → 客户端拿到 loginToken | RSA 私钥 | `secrets/jverify_rsa_private.pem`(PKCS#8,不入 git,`JG_PRIVATE_KEY_PATH` 指定,懒加载) | > **密钥对配对关系是关键**:极光用控制台上传的公钥加密,后端必须用**配对的私钥**解密。私钥不配对时 `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,换公钥会使其旧私钥失效,需同步部署新私钥。 +> **2026-05-27 现状**:历史遗留的两套本地密钥均**不配对**当前 AppKey 公钥,已重新生成一对 1024-bit/PKCS#8 密钥,公钥需在极光控制台更新。⚠️ 该 AppKey 公钥为全局配置,若占坑版后端仍在用同一 AppKey,换公钥会使其旧私钥失效,需同步部署新私钥。 ### 4.2 短信登录(mock 路径) @@ -147,7 +150,25 @@ POST /api/v1/auth/sms/login { phone, code } → 任意 6 位通过 → upsert --- -## 6. 数据模型 +## 6. 领券透传(coupon/step) + +产品"一键领券"的核心接入点,但**真正的领券逻辑不在本服务**——在另一个 repo `pricebot-backend`(GoalEngine + 事件驱动)。本服务只做"鉴权 + 透传壳"。 + +``` +客户端 → POST /api/v1/coupon/step (Bearer access_token + 任意 JSON body) + → coupon.py:get_current_user 校验 JWT(唯一需鉴权的业务接口) + → async httpx 把 body 原样 POST 到 PRICEBOT_BASE_URL/api/coupon/step + → 把 pricebot 的响应原样返回 +``` + +- **不做 schema 校验**:body 原样透传,pricebot 自己校验(后端仅读 `trace_id`/`step` 打日志)。 +- **错误**:body 非合法 JSON → 400;pricebot 不可达或返回 5xx → 502。 +- **配置**:`PRICEBOT_BASE_URL`(默认 `http://localhost:8000`)、`PRICEBOT_REQUEST_TIMEOUT_SEC`(默认 30s,因领券单帧最多 wait 6s)。 +- **现状**:接口已挂载可用,但**前端 ComparingScreen 仍是动画 demo、尚未对接此接口**;pricebot-backend 不在本目录。 + +--- + +## 7. 数据模型 仅一张 `user` 表(`models/user.py`): @@ -165,32 +186,30 @@ POST /api/v1/auth/sms/login { phone, code } → 任意 6 位通过 → upsert --- -## 7. 配置与部署 +## 8. 配置与部署 -配置见 `core/config.py`(pydantic-settings 读 `.env`)。分组:环境、`DATABASE_URL`、JWT、极光(`JG_*`)、短信(`SMS_MOCK` 默认 true)、美团(`MT_CPS_*`)、CORS。 +配置见 `core/config.py`(pydantic-settings 读 `.env`)。分组:环境、`DATABASE_URL`、JWT、极光(`JG_*`)、短信(`SMS_MOCK` 默认 true)、美团(`MT_CPS_*`)、**pricebot 上游(`PRICEBOT_BASE_URL` / `PRICEBOT_REQUEST_TIMEOUT_SEC`)**、CORS。 **生产部署**: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 -# 同步代码(排除虚拟环境/数据/私钥) 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/ -# 迁移 + 重启 +scp secrets/jverify_rsa_private.pem server:/opt/shaguabijia-app-server/secrets/ # 私钥单独传,不入 git ssh server "cd /opt/shaguabijia-app-server && .venv/bin/alembic upgrade head && systemctl restart shaguabijia-app-server" ``` **生产 checklist(均为上线必查)**: -- [ ] `JWT_SECRET_KEY` 改为高熵随机串(`python -c "import secrets;print(secrets.token_urlsafe(64))"`)——默认值 `change-me` 可被伪造 token +- [ ] `JWT_SECRET_KEY` 改为高熵随机串——默认值 `change-me` 可被伪造 token - [ ] `SMS_MOCK=false` 并接真实短信供应商——mock 下任意 6 位码可登录任意手机号 - [ ] `MT_CPS_APP_KEY` / `MT_CPS_APP_SECRET` 已填(否则美团接口 502) +- [ ] `PRICEBOT_BASE_URL` 指向真实 pricebot-backend(否则领券 502) - [ ] RSA 私钥就位且与极光控制台公钥**配对**,权限 600 - [ ] `APP_ENV=prod`、`APP_DEBUG=false`、nginx SSL 有效、`alembic upgrade head` 已执行 --- -## 8. 本地联调(真机) +## 9. 本地联调(真机) ```bash conda activate price # 首次:pip install -e . @@ -205,14 +224,16 @@ conda activate price # 首次:pip install -e . --- -## 9. 已知问题与后续 +## 10. 已知问题与后续 | 项 | 说明 | |---|---| | logout 无服务端失效 | 靠客户端清 token;后续加 jti 黑名单表 | | 美团接口无鉴权 + sid 可覆盖 | 评估加鉴权/锁定 sid(注意首页要求未登录可见) | | feed 静默吞异常 | 建议给 `_fetch_topic` 加日志,避免无声失败 | +| 领券依赖 pricebot | `coupon/step` 仅透传,真正逻辑在 pricebot-backend;前端尚未对接 | | SMS 为 mock | 上线接真实供应商 + `SMS_MOCK=false` | | 短信冷却存内存 | 扩 worker 前需迁移到 Redis | | SQLite | 流量上来切 PostgreSQL,只改 `DATABASE_URL` | -| 文档可观测性 | API 协议见 `API.md`,以代码为准 | + +> 完整接口协议(11 个)见 [`docs/api/`](./api/),以代码为准。 From a07361007f85152550175fe7d465caed4c00a644 Mon Sep 17 00:00:00 2001 From: marco Date: Wed, 27 May 2026 12:13:58 +0800 Subject: [PATCH 3/5] =?UTF-8?q?docs:=20=E6=96=B0=E5=A2=9E=20docs/README.md?= =?UTF-8?q?=20=E6=96=87=E6=A1=A3=E5=BA=93=E5=AF=BC=E8=88=AA(=E8=AF=B4?= =?UTF-8?q?=E6=98=8E=20api/=20=E4=BC=A0=E9=80=81=E9=97=A8=E7=BB=93?= =?UTF-8?q?=E6=9E=84)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - docs/README.md: 说明文档库结构(后端技术实现.md + api/), 重点讲 api/ 的 "索引 + 一接口一文件"传送门组织方式, 及新增接口时的维护约定 Co-Authored-By: Claude Opus 4.7 (1M context) --- docs/README.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 docs/README.md diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..928ca30 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,21 @@ +# 后端文档库(docs/) + +`shaguabijia-app-server` 的文档都在这里。各文档作用: + +| 文档 / 目录 | 作用 | +|---|---| +| [后端技术实现.md](./后端技术实现.md) | **后端技术方案**:业务概览、分层架构与目录、登录链路、美团 CPS、领券透传、数据模型、配置与部署、已知问题。想了解"整个后端怎么回事"看这份。 | +| [api/](./api/) | **API 接口文档**(目录),采用"索引 + 一接口一文件",结构见下。想查"某个接口的协议"看这里。 | + +## api/ 目录是怎么组织的(传送门式) + +接口多了之后,单个大文件会臃肿、难维护,所以拆成 **一个索引 + 一个接口一个文件**: + +- **[api/README.md](./api/README.md) — 入口/传送门** + 一张总览表列出**全部接口**(方法、路径、鉴权),每行链接到该接口的独立文档;另含**通用约定**(错误码、时间格式等)和**复用数据结构**(`TokenPair` / `UserOut` / `CouponCard` 等)。它本身不展开每个接口的细节,只负责"指路"。 +- **api/<模块>-<接口>.md — 单接口文档** + 每个接口一个文件,只写自己的入参 / 出参 / 错误码 / 说明。命名按 `<模块>-<接口>`,如 `auth-jverify-login.md`、`coupon-step.md`、`meituan-feed.md`。 + +**查某个接口的协议**:先打开 [api/README.md](./api/README.md) 的总览表 → 找到接口 → 点链接进对应文档。 + +> **新增接口时**:在 `api/` 下加一个 `<模块>-<接口>.md`,并到 `api/README.md` 总览表里补一行链接。这样索引始终是唯一的"传送门",细节各自独立、互不干扰。 From a188c43bf79cf7cb92273d7eb3b1023d1af8431b Mon Sep 17 00:00:00 2001 From: marco Date: Wed, 27 May 2026 12:26:58 +0800 Subject: [PATCH 4/5] =?UTF-8?q?=E6=8A=80=E6=9C=AF=E5=80=BA=E6=96=87?= =?UTF-8?q?=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/README.md | 1 + docs/待办与技术债.md | 48 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 docs/待办与技术债.md diff --git a/docs/README.md b/docs/README.md index 928ca30..9f40fc7 100644 --- a/docs/README.md +++ b/docs/README.md @@ -6,6 +6,7 @@ |---|---| | [后端技术实现.md](./后端技术实现.md) | **后端技术方案**:业务概览、分层架构与目录、登录链路、美团 CPS、领券透传、数据模型、配置与部署、已知问题。想了解"整个后端怎么回事"看这份。 | | [api/](./api/) | **API 接口文档**(目录),采用"索引 + 一接口一文件",结构见下。想查"某个接口的协议"看这里。 | +| [待办与技术债.md](./待办与技术债.md) | **待办与技术债账本**:记"现在先简化、以后要补"的事 + 跨前后端技术债(P1 鉴权/用户绑定、引擎移植待办等),免遗忘。想知道"还欠什么、以后要补什么"看这份。 | ## api/ 目录是怎么组织的(传送门式) diff --git a/docs/待办与技术债.md b/docs/待办与技术债.md new file mode 100644 index 0000000..4438abf --- /dev/null +++ b/docs/待办与技术债.md @@ -0,0 +1,48 @@ +# 待办与技术债账本 + +> 用途:记"现在先简化、以后要补"的事,和暂不处理的技术债,免得忘。每条标优先级 + 触发背景。做掉的移到末尾「已解决」。 +> 范围:跨栈账本——本仓 `shaguabijia-app-server`(转发层) + `shaguabijia-app-android`(无障碍引擎移植) + `pricebot-backend`(agent 上游,不改)。 +> 大背景:把"后端当大脑、无障碍服务遥控前端操作其它 App"的比价/领券引擎,从 demo app `pricebot` 移植进正式版傻瓜比价。引擎移植采用「代码全搬、独立子包 `…shaguabijia.agent.*`、验证分步(先领券后比价)」。 +> 最后更新:2026-05-27 + +--- + +## P1 · 鉴权与用户绑定(最该补) + +- **现状**:agent 系列接口 MVP 阶段**全部不鉴权**——领券 `coupon/step` + 比价 4 个(`intent/recognize`、`price/step`、`ecom/intent/recognize`、`ecom/step`)。落地时现有 `coupon-step` 路由的 `CurrentUser` 依赖要先去掉。 +- **代价(为什么记这笔账)**:不验 JWT → 转发时 server 拿不到 `user_id` → agent 行为只能绑到 `device_id`(设备级),**采集不到"哪个用户领了/买了什么"的用户级画像**。而精准人群画像、私域分群运营是商业模式的核心资产,靠的就是这份用户级行为数据。`device_id` 仍照传(后端按设备串领券队列够用)。 +- **待补**:① agent 接口加 JWT 鉴权;② 建立 `device_id ↔ user_id` 绑定(登录后上报一次即可);③ 领券/比价记录按 user 维度落库。 +- **连带**:补鉴权后,客户端引擎 `ApiClient` 要接回 JWT(复用 app 现有 `AuthInterceptor` 思路:注入带鉴权头的 OkHttpClient)。 + +--- + +## P2 · 引擎移植 · 后端转发层(本仓) + +- **加 4 个比价透传端点**:`intent/recognize`、`price/step`、`ecom/intent/recognize`、`ecom/step`。仿 `coupon_step` **纯 body 透传、不加 Pydantic schema**(协议归 pricebot 校验,否则它一改字段本仓就得跟着改,白白耦合)。client `/api/v1/xxx` → 转发 backend `/api/xxx`(去掉 v1,同 `coupon_step`)。 +- **转发超时要调大**:`coupon_step` 现 `PRICEBOT_REQUEST_TIMEOUT_SEC=30`(领券单帧 wait 6s)。但意图识别是一次大上下文 LLM、`price/step` 每帧也是 LLM,可能 >30s;客户端 `ApiClient` 读超时是 60s。→ 转发超时对齐 60s,**待测 pricebot 各接口真实耗时**再定终值。 +- **生产 server 与 backend 同内网**:`PRICEBOT_BASE_URL` 部署时设内网地址。比价是 30~80 步循环,每步多一跳,走公网延迟会累积。 +- **nginx body 上限**:比价 debug 包带 `screenshot`(webp base64,几百 KB)。若 debug 联调走线上域名经 nginx,注意 `client_max_body_size`(release 不带截图、debug 直连本地都无此问题,仅"debug 走域名"才撞)。 + +--- + +## P2 · 引擎移植 · 客户端(android 仓,在此备忘) + +- **无障碍身份统一为傻瓜比价**:服务名/图标自动继承 application(`` 不单独设 label/icon);需显式改的 3 处文案——`accessibility_service_description`、前台常驻通知文案("PriceBot 正在待命"等)、`GuideCopy` 里引导高亮的系统列表条目名("PriceBot"→"傻瓜比价")。 +- **BuildConfig 包名**:代码里 `com.pricebot.app.BuildConfig` 的 import 必须改成本 app 包名,否则编译不过。 +- **领券入口**:首页"一键领券"从 `ComparingScreen` 假动画 → 真 `startCouponClaim()`。 +- **比价悬浮球**:`SUPPORTED_BIZ_PACKAGES`(购物 App 前台才显示悬浮球)逻辑照搬。 +- **权限引导融入 Compose**:把 pricebot `MainActivity` 里申请无障碍/悬浮窗/电池优化的逻辑抽出,接到傻瓜比价的 Compose 页(权限引导 Activity 那几个可照搬,改包名+文案)。 +- **类名可选改名**:`PriceBotService` 等用户不可见,保留无妨;想整洁可改 `ShaguaAccessibilityService`(牵动引用,不急)。 + +--- + +## 技术债(暂不处理,知情即可) + +- **agent 接口公网裸奔**:不鉴权 = 任何人可调,烧 pricebot 的 LLM 算力。与美团 3 接口现状同级,记账后随 P1 一起补。 +- **既有债(已记录在别处)**:美团 `referral-link` 的 `sid` 客户端可覆盖刷分佣;`logout` 占位不吊销 token;`SMS_MOCK=true` 全站免密登录;`JWT_SECRET_KEY` 默认值可伪造 token。详见 [后端技术实现.md](./后端技术实现.md) 与 [api/](./api/)。 + +--- + +## 已解决 + +(暂无) From 007f8a0eb2487442d6549bf775795401d66117dd Mon Sep 17 00:00:00 2001 From: marco Date: Wed, 27 May 2026 16:38:10 +0800 Subject: [PATCH 5/5] =?UTF-8?q?feat:=20coupon/step=20=E9=80=8F=E4=BC=A0?= =?UTF-8?q?=E5=8E=BB=E9=89=B4=E6=9D=83(MVP)=20+=20=E6=8A=80=E6=9C=AF?= =?UTF-8?q?=E5=80=BA=E8=B4=A6=E6=9C=AC=E8=A1=A5=E5=85=85=E9=A2=86=E5=88=B8?= =?UTF-8?q?=E8=90=BD=E5=9C=B0=E9=81=97=E7=95=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - /api/v1/coupon/step 去掉 CurrentUser 鉴权:MVP 领券不鉴权,device_id 透传给 pricebot 区分设备;user_id 绑定 + 用户级画像见账本 P1,待补 - docs/待办与技术债.md 补「阶段1领券落地遗留」:FloatingButton 死代码、ComparingScreen 弃用、ApiClient unused 常量、权限引导最简版等待清理项 Co-Authored-By: Claude Opus 4.7 (1M context) --- app/api/v1/coupon.py | 12 ++++++------ docs/待办与技术债.md | 8 ++++++++ 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/app/api/v1/coupon.py b/app/api/v1/coupon.py index f91327f..29ba79c 100644 --- a/app/api/v1/coupon.py +++ b/app/api/v1/coupon.py @@ -1,7 +1,9 @@ """领券业务透传端点。 把客户端的 POST /api/v1/coupon/step 请求原样转发给 pricebot-backend -的 /api/coupon/step,只在外层加 JWT 鉴权。 +的 /api/coupon/step。MVP 阶段**不鉴权**(见 docs/待办与技术债.md P1: +device_id 透传给 pricebot 区分设备,待补 JWT + device_id↔user_id 绑定后 +才能做用户级画像)。 pricebot 协议文档: pricebot-backend/docs/projects/领券-客户端对接协议.md @@ -14,7 +16,6 @@ from typing import Any import httpx from fastapi import APIRouter, HTTPException, Request, status -from app.api.deps import CurrentUser from app.core.config import settings logger = logging.getLogger("shagua.coupon") @@ -25,11 +26,10 @@ router = APIRouter(prefix="/api/v1/coupon", tags=["coupon"]) @router.post("/step", summary="领券任务步进 (透传到 pricebot)") async def coupon_step( request: Request, - user: CurrentUser, ) -> dict[str, Any]: """把请求体原样转发给 pricebot-backend 的 /api/coupon/step。 - - 鉴权: Bearer access_token (get_current_user 隐式校验) + - 鉴权: MVP 阶段不鉴权(待补 JWT,见 docs/待办与技术债.md P1) - 透传: 不做 schema 校验,pricebot 自己校验 - 失败: 网络不可达 / pricebot 5xx → 502 + 友好 message """ @@ -42,8 +42,8 @@ async def coupon_step( timeout = settings.PRICEBOT_REQUEST_TIMEOUT_SEC logger.info( - "coupon_step user_id=%d trace_id=%s step=%s", - user.id, + "coupon_step device_id=%s trace_id=%s step=%s", + body.get("device_id"), body.get("trace_id"), body.get("step"), ) diff --git a/docs/待办与技术债.md b/docs/待办与技术债.md index 4438abf..444554c 100644 --- a/docs/待办与技术债.md +++ b/docs/待办与技术债.md @@ -43,6 +43,14 @@ --- +## 阶段 1 领券落地后的遗留(待清理,不阻塞跑通) + +- **FloatingButton 死代码**:Running 面板已换成 ComposeView 承载 `CouponProgressPanel`(=复用 AgentFloat)。旧原生面板字段(`line1~4View`/`elapsedView`/`progressBarView`/`historyContainerView` 等)+ `updateStatus(StepStatus)` 里保留的那段更新逻辑 + `appendActionLine`/`markCurrentActionDone`/`markPlatformDone`/`addCancelButton` 全部 no-op,待删。 +- **ComparingScreen / CompResultScreen 弃用**:领券改走悬浮窗,不再走全屏假动画。`Routes.COMPARING` / `COMP_RESULT` 成死路由,连同两个 Screen 文件待删(`CouponPromptDialog` 已抽到 `ui/coupon/`,删 ComparingScreen 不影响它)。 +- **ApiClient 常量 unused**:`getBackendUrl()` 改用 `BuildConfig.BASE_URL` 后,`DEFAULT_BACKEND_URL`/`KEY_BACKEND_URL` 常量 unused,待清。 +- **权限引导是最简版**:缺权限时直接跳系统设置页(`ACTION_ACCESSIBILITY_SETTINGS` / overlay 设置)。搬来的仿腾讯引导(`AccessibilityGuideActivity`/`PermissionGuide*`)尚未接入,体验后续可升级。 +- **领券大数字语义**:悬浮窗左侧"已领券"大数字目前接 `progress.current`(正在领第几张),非"已成功数"。中间帧后端不回传已领明细,要精确需后端在 status.progress 加 `completed[]`(协议文档第四节已留扩展点)。 + ## 已解决 (暂无)