From 932f912087aaabf1504dfceac9718a68a1ed5fe4 Mon Sep 17 00:00:00 2001 From: Eric Date: Sat, 24 Oct 2026 20:14:31 +0800 Subject: [PATCH] =?UTF-8?q?=EF=BB=BFShip=20WeChat=20VIP=E2=86=94Web=20brid?= =?UTF-8?q?ge,=20netdisk=20sheet,=20and=20per-lesson=20materials=20gate=20?= =?UTF-8?q?for=20audit.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Freeze pre4 as the in-review weapp package; document pre5 as the next iteration branch. Co-authored-by: Cursor --- .cursor/rules/multi-platform-ui-scale.mdc | 17 + .cursor/rules/ui-ux.mdc | 1 + .../skills/multi-platform-ui-scale/SKILL.md | 60 ++ README.md | 36 +- apps/admin/src/pages/Vip.tsx | 86 ++ apps/api/.env.example | 4 + apps/api/app/main.py | 2 + apps/api/services/ebook_svc/config.py | 5 + apps/api/services/ebook_svc/main.py | 2 + apps/api/services/ebook_svc/routers/auth.py | 152 +++- .../services/ebook_svc/routers/vip_admin.py | 1 + .../services/ebook_svc/routers/vip_bridge.py | 207 +++++ apps/api/services/ebook_svc/services/store.py | 43 + .../services/ebook_svc/services/vip_config.py | 5 + .../ebook_svc/services/vip_content.py | 80 ++ .../ebook_svc/services/vip_web_bridge.py | 197 +++++ apps/miniprogram/h5/src/app.config.ts | 6 + .../h5/src/components/MiniModuleGate.tsx | 15 +- .../h5/src/components/NetdiskShareModal.scss | 164 ++++ .../h5/src/components/NetdiskShareModal.tsx | 76 ++ .../h5/src/components/VipLoginModal.scss | 227 +++++ .../h5/src/components/VipLoginModal.tsx | 224 +++++ .../h5/src/data/remoteConfig.defaults.ts | 3 + apps/miniprogram/h5/src/data/vipContent.ts | 137 ++- apps/miniprogram/h5/src/data/vipCourse.ts | 31 +- apps/miniprogram/h5/src/pages/mine/index.tsx | 5 +- .../h5/src/pages/vip-account/index.config.ts | 7 + .../h5/src/pages/vip-account/index.scss | 279 ++++++ .../h5/src/pages/vip-account/index.tsx | 236 +++++ .../h5/src/pages/vip-course/index.tsx | 9 +- .../h5/src/pages/vip-ebook/index.tsx | 19 +- .../h5/src/pages/vip-lesson/index.tsx | 168 +++- apps/miniprogram/h5/src/pages/vip/index.tsx | 807 ++++++++++-------- .../miniprogram/h5/src/services/vipLibrary.ts | 49 +- .../h5/src/styles/vip-landing.scss | 85 ++ .../h5/src/utils/accountBlocked.ts | 41 + apps/miniprogram/h5/src/utils/request.ts | 22 +- .../miniprogram/h5/src/utils/vipWebAccount.ts | 88 ++ apps/miniprogram/weapp/README.md | 17 +- apps/miniprogram/weapp/config/index.ts | 8 +- src/lib/remote-config.ts | 9 - 41 files changed, 3166 insertions(+), 464 deletions(-) create mode 100644 .cursor/rules/multi-platform-ui-scale.mdc create mode 100644 .cursor/skills/multi-platform-ui-scale/SKILL.md create mode 100644 apps/api/services/ebook_svc/routers/vip_bridge.py create mode 100644 apps/api/services/ebook_svc/services/vip_web_bridge.py create mode 100644 apps/miniprogram/h5/src/components/NetdiskShareModal.scss create mode 100644 apps/miniprogram/h5/src/components/NetdiskShareModal.tsx create mode 100644 apps/miniprogram/h5/src/components/VipLoginModal.scss create mode 100644 apps/miniprogram/h5/src/components/VipLoginModal.tsx create mode 100644 apps/miniprogram/h5/src/pages/vip-account/index.config.ts create mode 100644 apps/miniprogram/h5/src/pages/vip-account/index.scss create mode 100644 apps/miniprogram/h5/src/pages/vip-account/index.tsx create mode 100644 apps/miniprogram/h5/src/utils/accountBlocked.ts create mode 100644 apps/miniprogram/h5/src/utils/vipWebAccount.ts diff --git a/.cursor/rules/multi-platform-ui-scale.mdc b/.cursor/rules/multi-platform-ui-scale.mdc new file mode 100644 index 0000000..611286b --- /dev/null +++ b/.cursor/rules/multi-platform-ui-scale.mdc @@ -0,0 +1,17 @@ +--- +description: 多端 UI 比例铁律 — Web/微信/抖音/小红书;禁止把 Web px 弹窗原样搬进小程序 +alwaysApply: true +--- + +# 多端 UI 比例(强制) + +**Web 只参考结构;尺寸必须按端适配。** 详情见 `.cursor/skills/multi-platform-ui-scale/SKILL.md`。 + +| 端 | 要点 | +|----|------| +| Web VIP | 可居中 `max-w-[400px]` | +| Taro H5/weapp/tt/xhs | `designWidth: 750`;**裸 `px` → rpx 会缩水**;弹窗/表单用 **`rem` 或 `rpx`** | +| 小程序弹窗 | **全宽底栏** + 触控 ≥44px;勿抄 Web 桌面小卡片 | + +反模式:VIP LoginModal 在微信里变成拇指盖大的居中框。 +正确参考:`apps/miniprogram/h5/src/components/VipLoginModal.scss`、`vip-landing.scss`。 diff --git a/.cursor/rules/ui-ux.mdc b/.cursor/rules/ui-ux.mdc index 54f4759..67a01d7 100644 --- a/.cursor/rules/ui-ux.mdc +++ b/.cursor/rules/ui-ux.mdc @@ -9,5 +9,6 @@ alwaysApply: true - 视觉:充分使用 emoji / SVG / CSS 动画 / JS 动效;图表可用 D3;3D/沉浸可用 three.js、WebGL、WebVR;优先考虑 WASM / PWA - 反模式:勿用 AI 默认紫渐变、奶油衬线、报纸密栏;门户首屏品牌优先、少卡片堆砌 - 响应式:移动优先,PC/H5 双端;触控热区约 44px +- **多端比例**:Web 只参考结构;微信/抖音/小红书/Taro 禁止照抄 Web 桌面 `px` 弹窗(`designWidth: 750` 会缩水)。见 `multi-platform-ui-scale` skill + rule - 社媒引导:海外弹 X 关注;中文弹公众号二维码 - VIP 参考色:琥珀强调 `#f59e0b`,夜间底 `#0c0c0f`(见 `src/modules/vip`) diff --git a/.cursor/skills/multi-platform-ui-scale/SKILL.md b/.cursor/skills/multi-platform-ui-scale/SKILL.md new file mode 100644 index 0000000..1b5d6dc --- /dev/null +++ b/.cursor/skills/multi-platform-ui-scale/SKILL.md @@ -0,0 +1,60 @@ +--- +name: multi-platform-ui-scale +description: >- + Nomadro 多端 UI 比例与 CSS 单位铁律:Web / H5 / 微信小程序 / 抖音小程序 / 小红书。 + 写或改任何弹窗、按钮、落地页、VIP LoginModal、Taro 样式时必须遵守; + 禁止把 Web 桌面尺寸原样搬到小程序导致弹窗缩成一团。 +--- + +# 多端 UI 比例铁律(写死,勿再问) + +## 一句话 + +**Web 只参考结构与信息架构;最终尺寸必须按当前端的触控与单位体系适配。禁止「照抄 Web 的 px 弹窗」到微信/抖音/小红书。** + +## 端与技术 + +| 端 | 路径 | 单位 / 设计稿 | +|----|------|----------------| +| Web 门户 VIP | `src/modules/vip` | CSS / Tailwind;桌面可居中 `max-w-[400px]` | +| Taro H5 SoT | `apps/miniprogram/h5` | 与落地页一致优先 **`rem`**(对齐 vip-landing) | +| 微信 weapp | `apps/miniprogram/weapp` · `designWidth: 750` | **裸写 `px` 会被转成 rpx → 尺寸腰斩** | +| 抖音 tt | `apps/miniprogram/tt` · `designWidth: 750` | 同 weapp | +| 小红书 xhs | `apps/miniprogram/xhs` | 同 Taro 750;纯工具页离线优先 | + +H5 SoT 共用源码:`weapp/tt` 的 `sourceRoot` 指向 `../h5/src` —— **一处样式四端吃**,写样式时按「最严端(小程序)」适配。 + +## 强制规则 + +1. **小程序 / Taro 共用样式** + - 弹窗、表单、CTA:**用 `rem`(与 `vip-landing.scss` 同尺度)或显式 `rpx`** + - **禁止**在共用 SCSS 里写死 Web 桌面感的 `max-width: 400px` + 一堆裸 `px`(会被 750 稿压成拇指盖大的卡片) + - 触控热区:**≥ 44px 等价**(约 `2.75rem` / `88rpx`) + - 手机弹窗:**全宽底栏 sheet**(`align-items: flex-end` + 顶圆角);宽屏再可居中。不要默认桌面居中小卡片。 + +2. **Web VIP LoginModal** + - 仅参考:**标题「登录」+ Tab「账号/邮箱」+ 输入 +「验证并登录」+ 验证中全屏层** + - **不要**把 Web 的 `max-w-[400px]` 居中小卡原样搬进小程序 + - 不要加品牌眉、副标题、字段标签等「超级优化」花活,除非产品明确要求 + +3. **参考 ≠ 复制尺寸** + - 结构、文案、交互流:可对齐 Web + - padding / font / 宽度 / 圆角:**按小程序重算** + +4. **改弹窗前自检** + - [ ] 微信模拟器里弹窗是否接近屏宽、按钮是否好点 + - [ ] 是否误用裸 `px` 导致缩水 + - [ ] H5 / weapp / tt 是否同源样式、比例一致 + +## 反模式(禁止) + +- 把 Web `LoginModal` 的 Tailwind 间距原样抄成 Taro `px` +- 小程序里居中一块「桌面对话框」又细又小 +- 用户每次提醒「比例」才改 —— 本 skill 已写死,开工先遵守 + +## 关联 + +- 全端禁止 web-view:`.cursor/rules/no-webview-content.mdc` +- 远程配置 + 离线:`.cursor/rules/remote-config-offline.mdc` +- 现成正确示例:`apps/miniprogram/h5/src/components/VipLoginModal.scss`(rem + 底栏) + `apps/miniprogram/h5/src/styles/vip-landing.scss` diff --git a/README.md b/README.md index 669a239..4f653c3 100644 --- a/README.md +++ b/README.md @@ -115,24 +115,30 @@ pnpm dev:api - **远程配置 + 离线兜底**:`/api/config` · `data/remote-config.json` · `/admin/config` - **禁止**再引入已删垂直树(见 `AGENTS.md`) - **发布流**:本地调试 → 当前开发分支 commit/push → 部署脚本上线 → 冒烟;配置与发版均以 git 为准 -- 主开发分支:`pre4`(`pre3` 已封存本轮);发版前与 README / 远程对齐 +- 审核冻结分支:`pre4`(**当前微信版本已提交上线审核,勿在本分支继续功能迭代**) +- 下一轮开发分支:`pre5`(从 `pre4` 拉出);发版前与 README / 远程对齐 -## pre4 摘要 +## pre4 摘要(审核包) -- 微信启动页 **`pages/home/index`**(话题/体验码同路径);`pages/index` 兼容 `reLaunch` → home -- 本轮标记:**`20261011-2`**(审核候选;承接 `20261011b` 路径 + `20261011` 视觉) +- 微信启动页 **`pages/home/index`**;`pages/index` 兼容 `reLaunch` → home +- 本轮标记:**`20261011-2`**(审核中;承接 `20261011b` 路径 + `20261011` 视觉) +- **VIP ↔ Web 账号打通(增量,默认关)** + - Flag:`flags.vipWebBridgeEnabled`(后台 VIP 运营可开;`VIP_WEB_BRIDGE_ENABLED` 可强开) + - 小程序:`VipLoginModal`(rem 底栏)· `pages/vip-account`;已绑定不展示废按钮/支付 hint + - API:`/api/ebook/auth/vip-web-login` · `vip-bind-email` · `vip-bridge-status`(只读校验 vip.hackrobot.cn) +- **网盘 / 课时资料** + - VIP 落地:`netdisk` 列表 + `NetdiskShareModal`(对齐 Web 分享弹窗结构,小程序全宽底栏) + - 课时页:默认**不**展示资料;仅 `lessonMaterials[课时key]` 单独配了 `url` 才显示 +- **多端 UI 比例**:`.cursor/skills/multi-platform-ui-scale` + rule(Web 只参考结构,小程序用 rem/rpx) +- **课时播放**:视频 URL 编码空格/中文;本地片源先起播,不挡 `forceRefresh` - **审核前修复(`20261011-2`)** - - VIP「Youtube运营笔记」→ `reader?id=default`(后台「内容→VIP→电子书→youtube运营笔记」),禁止误进数字游民 `vip-ebook?id=nomad` - - `vipContent.ebooks` 默认含 youtube-notes;服务端 `_ensure_youtube_notes_ebook` 校正 href - - 提审开关只影响数字游民,不劫持 `book_id=default` - - 「VIP 中心」开关与加群联动:开→跳会员页,关→公众号弹窗;加群点击强制拉最新 `/api/config` -- **P0/P1 加固**(已在 `017008d`) - - 统一 API 挂载 VIP library / weapp switches;VIP 正文需鉴权(目录可匿名) - - Mine 统一 ebook 登录(`ensureLogin` / `clearLogin`) - - weapp game:`index.weapp.tsx` stub + `IgnorePlugin(three)`,无 Three.js 包体 - - SQLite WAL + busy_timeout;login / pay / track 限流 - - CORS 白名单;本地自动 `.env`(`run.py`)与非生产默认 `DEBUG`/devtools;生产设 `NOMADRO_ENV=production` - - 社区 API 默认 `https://api.nomadro.cn/api/v1`;`WechatOaModal` 进 `pxExclude` + - VIP「Youtube运营笔记」→ `reader?id=default`;提审开关不劫持 `book_id=default` + - VIP/加群开关联动;加群点击强制拉最新 `/api/config` +- **P0/P1 加固**(`017008d`):VIP library 鉴权、Mine 登录、game stub、WAL/限流、CORS + +## pre5(下一轮) + +从 `pre4` 切出;**勿改动审核包行为**,仅做下一版本功能。建议方向:课时资料后台可视化编辑、桥接 UX 打磨、DevTools Timeout 排查(真机网络/域名)。 ## pre3 摘要(已合入) diff --git a/apps/admin/src/pages/Vip.tsx b/apps/admin/src/pages/Vip.tsx index d6a562f..58ab8a8 100644 --- a/apps/admin/src/pages/Vip.tsx +++ b/apps/admin/src/pages/Vip.tsx @@ -61,6 +61,9 @@ type VipContent = { faqSub: string ctaChips: string[] ctaSecondary: string + /** 空则课时页不展示「课程资料下载」 */ + courseMaterialsUrl: string + courseMaterialsDesc: string } type VipCfg = { @@ -68,6 +71,7 @@ type VipCfg = { vipEnabled: boolean gameEnabled: boolean joinGroupAction: JoinAction + vipWebBridgeEnabled?: boolean vipPriceFen: number vipProductId: string vipCta: string @@ -112,12 +116,15 @@ const emptyContent: VipContent = { faqSub: '购买前可快速了解会员权益与流程', ctaChips: ['阶梯定价', '数字交付', '持续更新', '不支持退款'], ctaSecondary: '已有账号', + courseMaterialsUrl: '', + courseMaterialsDesc: '课程配套资料已上传至网盘,报名后可复制链接打开夸克获取', } const empty: VipCfg = { vipEnabled: false, gameEnabled: false, joinGroupAction: 'popup', + vipWebBridgeEnabled: false, vipPriceFen: 29800, vipProductId: 'tiktok', vipCta: '立即加入', @@ -205,6 +212,10 @@ function fromContent(raw: Partial | undefined): VipContent { videos: Array.isArray(c.videos) ? c.videos : [], ebooks: Array.isArray(c.ebooks) ? c.ebooks : [], ctaChips: Array.isArray(c.ctaChips) ? c.ctaChips : emptyContent.ctaChips, + courseMaterialsUrl: String(c.courseMaterialsUrl || '').trim(), + courseMaterialsDesc: String( + c.courseMaterialsDesc || emptyContent.courseMaterialsDesc, + ), } } @@ -213,6 +224,7 @@ function fromApi(data: VipCfg): VipCfg { vipEnabled: !!data.vipEnabled, gameEnabled: !!data.gameEnabled, joinGroupAction: data.joinGroupAction === 'vip' ? 'vip' : 'popup', + vipWebBridgeEnabled: !!data.vipWebBridgeEnabled, vipPriceFen: Number(data.vipPriceFen) || 0, vipProductId: String(data.vipProductId || ''), vipCta: String(data.vipCta || '立即加入'), @@ -314,6 +326,7 @@ export default function Vip() { vipEnabled: next.vipEnabled, gameEnabled: next.gameEnabled, joinGroupAction: next.joinGroupAction, + vipWebBridgeEnabled: !!next.vipWebBridgeEnabled, vipPriceFen: next.vipPriceFen, vipProductId: next.vipProductId, vipCta: next.vipCta, @@ -576,6 +589,27 @@ export default function Vip() { /> +
+
+ Web 账号打通 +

+ 开启后:小程序显示「已有账号」弹窗(对齐 Web 登录),付费后引导绑邮箱以便回 Web + 登录。默认关;只增量写当前 openid,不改既有订单与他人会员 +

+
+ + void save( + { vipWebBridgeEnabled: v }, + v ? 'Web 账号打通已开启' : 'Web 账号打通已关闭', + ) + } + /> +
+
数字游民 · 游戏入口 @@ -800,6 +834,58 @@ export default function Vip() { })}
+

单课时资料(可选)

+

+ 每个视频页默认不展示资料。仅当在 lessonMaterials 为该课时 key(如 + 0-0)单独配了 url 才显示。下方全局链接不会套到所有课时;落地页「网盘下载」仍走 + netdisk 列表。 +

+
+
+ + + updateContentLocal({ courseMaterialsUrl: e.target.value }) + } + onBlur={() => + patchContent( + { + courseMaterialsUrl: String( + content.courseMaterialsUrl || '', + ).trim(), + }, + content.courseMaterialsUrl?.trim() + ? '课程资料链接已保存' + : '已隐藏课程资料下载', + ) + } + /> +
+
+ + + updateContentLocal({ courseMaterialsDesc: e.target.value }) + } + onBlur={() => + patchContent( + { + courseMaterialsDesc: String( + content.courseMaterialsDesc || '', + ), + }, + '资料说明已保存', + ) + } + /> +
+
+

视频教程

{content.videos.map((t) => { diff --git a/apps/api/.env.example b/apps/api/.env.example index 8fa9fdb..e170c9f 100644 --- a/apps/api/.env.example +++ b/apps/api/.env.example @@ -1,2 +1,6 @@ DEBUG=true WX_ALLOW_DEVTOOLS_LOGIN=true + +# Web VIP ↔ 小程序打通(默认关,避免影响线上) +# VIP_WEB_BRIDGE_ENABLED=true +# VIP_WEB_API_BASE=https://vip.hackrobot.cn diff --git a/apps/api/app/main.py b/apps/api/app/main.py index 9c3326a..a808fe8 100644 --- a/apps/api/app/main.py +++ b/apps/api/app/main.py @@ -38,6 +38,7 @@ from ebook_svc.routers import ( # noqa: E402 shop_admin, track, vip_admin, + vip_bridge, vip_library_admin, vip_library_public, weapp_switches_admin, @@ -110,6 +111,7 @@ app.add_middleware( # —— 电子书 / 小程序(兼容 /api 与 /api/ebook)—— for _prefix in ("/api", "/api/ebook"): app.include_router(auth.router, prefix=_prefix) + app.include_router(vip_bridge.router, prefix=_prefix) app.include_router(books.router, prefix=_prefix) app.include_router(pay.router, prefix=_prefix) app.include_router(track.router, prefix=_prefix) diff --git a/apps/api/services/ebook_svc/config.py b/apps/api/services/ebook_svc/config.py index fae43dd..d42f21d 100644 --- a/apps/api/services/ebook_svc/config.py +++ b/apps/api/services/ebook_svc/config.py @@ -44,6 +44,11 @@ class Settings(BaseSettings): sqlite_path: str = "../data/nomadmini.db" + # Web VIP 桥接(vip.hackrobot.cn ↔ 小程序)— 默认关,避免误伤线上 + # 开启:环境变量 VIP_WEB_BRIDGE_ENABLED=true + vip_web_bridge_enabled: bool = False + vip_web_api_base: str = "https://vip.hackrobot.cn" + # 抖音 platforms.tt 写入路径(默认自动探测门户 remote-config.json) tt_remote_config_path: str = "" diff --git a/apps/api/services/ebook_svc/main.py b/apps/api/services/ebook_svc/main.py index 6f14630..1bb4296 100644 --- a/apps/api/services/ebook_svc/main.py +++ b/apps/api/services/ebook_svc/main.py @@ -26,6 +26,7 @@ from ebook_svc.routers import ( shop_admin, track, vip_admin, + vip_bridge, vip_library_admin, vip_library_public, ) @@ -56,6 +57,7 @@ app.add_middleware( # 门户 miniprogram:/api/ebook/*(同进程别名,共享 store) for _api_prefix in ("/api", "/api/ebook"): app.include_router(auth.router, prefix=_api_prefix) + app.include_router(vip_bridge.router, prefix=_api_prefix) app.include_router(books.router, prefix=_api_prefix) app.include_router(pay.router, prefix=_api_prefix) app.include_router(track.router, prefix=_api_prefix) diff --git a/apps/api/services/ebook_svc/routers/auth.py b/apps/api/services/ebook_svc/routers/auth.py index 0fe127d..7d04358 100644 --- a/apps/api/services/ebook_svc/routers/auth.py +++ b/apps/api/services/ebook_svc/routers/auth.py @@ -3,12 +3,14 @@ from __future__ import annotations import secrets from fastapi import APIRouter, Depends, HTTPException, Request +from pydantic import BaseModel, Field from ebook_svc.core.deps import get_current_openid from ebook_svc.core.rate_limit import rate_limit from ebook_svc.schemas.auth import LoginBody from ebook_svc.services.pocketbase import pb from ebook_svc.services.store import store +from ebook_svc.services import vip_web_bridge as bridge from ebook_svc.services.wxpay import code2session router = APIRouter(prefix="/auth", tags=["auth"]) @@ -16,6 +18,19 @@ router = APIRouter(prefix="/auth", tags=["auth"]) # 兼容旧 import 路径 __all__ = ["router", "get_current_openid", "LoginBody"] +VIP_BOOK_ID = "__vip__" + + +class VipWebLoginBody(BaseModel): + email: str | None = Field(default=None, max_length=200) + password: str | None = Field(default=None, max_length=200) + user_id: str | None = Field(default=None, max_length=80) + + +class VipWebBindBody(BaseModel): + email: str = Field(min_length=3, max_length=200) + password: str = Field(min_length=6, max_length=200) + @router.post("/login") async def login(body: LoginBody, request: Request): @@ -69,9 +84,144 @@ async def login(body: LoginBody, request: Request): async def presence_ping(openid: str = Depends(get_current_openid)): """小程序前台心跳:刷新 last_seen,并带回 isVip 供端上近实时刷新会员态。""" store.touch_last_seen(openid) + user = store.get_user(openid) or {} return { "ok": True, "openid": openid, "onlineWindowSec": store.ONLINE_WINDOW_SEC, - "isVip": store.is_unlocked(openid, "__vip__"), + "isVip": store.is_unlocked(openid, VIP_BOOK_ID), + "vipEmailBound": bool((user.get("vip_email") or "").strip()), + "bridgeEnabled": bridge.bridge_enabled(), + } + + +@router.get("/vip-bridge-status") +async def vip_bridge_status(openid: str = Depends(get_current_openid)): + """只读:桥接开关 + 当前用户绑定状态(不写库)。""" + user = store.get_user(openid) or {} + return { + "ok": True, + "bridgeEnabled": bridge.bridge_enabled(), + "isVip": store.is_unlocked(openid, VIP_BOOK_ID), + "vipEmail": (user.get("vip_email") or "").strip() or None, + "webUserId": (user.get("web_user_id") or "").strip() or None, + "vipEmailBound": bool((user.get("vip_email") or "").strip()), + } + + +@router.post("/vip-web-login") +async def vip_web_login( + body: VipWebLoginBody, + request: Request, + openid: str = Depends(get_current_openid), +): + """已有 Web VIP:邮箱密码只读校验 → 仅给当前 openid 写入本地 __vip__。 + + 不修改 web/PB 既有会员数据;失败不写库。 + """ + rate_limit(request, bucket="auth.vip_web_login", limit=12, window_sec=60.0) + if not bridge.bridge_enabled(): + raise HTTPException(503, "Web 账号打通未开启") + + if store.is_blocked(openid): + raise HTTPException(403, "账号不可用") + + email = (body.email or "").strip().lower() + password = (body.password or "").strip() + user_id = (body.user_id or "").strip() + + if email and password: + result = await bridge.check_web_vip_by_email( + email, + password, + user_id=user_id or None, + wechat_userid=openid, + ) + elif user_id: + result = await bridge.check_web_vip_by_user_id(user_id) + else: + raise HTTPException(400, "请填写邮箱密码,或输入会员账号") + + if not result.get("vip"): + raise HTTPException(401, str(result.get("error") or "验证失败")) + + # 仅本机当前 openid:发会员权益(幂等 upsert) + store.grant_unlock(openid, VIP_BOOK_ID, source="web_vip_login") + bound_email = str(result.get("email") or email or "").strip().lower() + web_uid = ( + (result.get("anonymousUserId") or result.get("effectiveUserId") or user_id or "") + or bridge.openid_to_web_user_id(openid) + ) + try: + store.ensure_web_user_id(openid, str(web_uid)) + if bound_email: + store.set_vip_email_bound(openid, bound_email, str(web_uid)) + except Exception: + pass + + return { + "ok": True, + "isVip": True, + "email": bound_email or None, + "source": "web_vip_login", + } + + +@router.post("/vip-bind-email") +async def vip_bind_email( + body: VipWebBindBody, + request: Request, + openid: str = Depends(get_current_openid), +): + """小程序已是 VIP 时绑定邮箱,便于反向登录 Web。 + + 安全:邮箱已是 Web 会员则拒绝(引导走 vip-web-login),不覆盖他人绑定。 + """ + rate_limit(request, bucket="auth.vip_bind_email", limit=8, window_sec=60.0) + if not bridge.bridge_enabled(): + raise HTTPException(503, "Web 账号打通未开启") + + if store.is_blocked(openid): + raise HTTPException(403, "账号不可用") + if not store.is_unlocked(openid, VIP_BOOK_ID): + raise HTTPException(403, "请先开通小程序 VIP 再绑定邮箱") + + user = store.get_user(openid) or {} + if (user.get("vip_email") or "").strip(): + return { + "ok": True, + "alreadyBound": True, + "email": (user.get("vip_email") or "").strip(), + "isVip": True, + } + + web_uid = store.ensure_web_user_id(openid, bridge.openid_to_web_user_id(openid)) + linked = await bridge.link_email_on_web(body.email, body.password, web_uid) + if not linked.get("ok"): + # alreadyVip:可直接走登录打通,仍不覆盖 web 数据 + if linked.get("alreadyVip"): + login = await bridge.check_web_vip_by_email( + body.email, body.password, wechat_userid=openid + ) + if login.get("vip"): + store.grant_unlock(openid, VIP_BOOK_ID, source="web_vip_login") + email = str(login.get("email") or body.email).strip().lower() + store.set_vip_email_bound(openid, email, web_uid) + return { + "ok": True, + "isVip": True, + "email": email, + "source": "web_vip_login", + "note": "邮箱已是 Web 会员,已打通小程序", + } + raise HTTPException(400, str(linked.get("error") or "绑定失败")) + + email = str(linked.get("email") or body.email).strip().lower() + store.set_vip_email_bound(openid, email, web_uid) + return { + "ok": True, + "isVip": True, + "email": email, + "webUserId": web_uid, + "source": "weapp_bind_email", } diff --git a/apps/api/services/ebook_svc/routers/vip_admin.py b/apps/api/services/ebook_svc/routers/vip_admin.py index 7e54920..5109478 100644 --- a/apps/api/services/ebook_svc/routers/vip_admin.py +++ b/apps/api/services/ebook_svc/routers/vip_admin.py @@ -16,6 +16,7 @@ class VipBody(BaseModel): vipEnabled: bool | None = None gameEnabled: bool | None = None joinGroupAction: Literal["popup", "vip"] | None = None + vipWebBridgeEnabled: bool | None = None vipPriceFen: int | None = Field(default=None, ge=0) vipProductId: str | None = None vipCta: str | None = None diff --git a/apps/api/services/ebook_svc/routers/vip_bridge.py b/apps/api/services/ebook_svc/routers/vip_bridge.py new file mode 100644 index 0000000..72a76ab --- /dev/null +++ b/apps/api/services/ebook_svc/routers/vip_bridge.py @@ -0,0 +1,207 @@ +"""Web VIP ↔ 小程序打通(独立路由,不改现有 auth.py)。 + +安全:默认关;登录只读校验 Web;只给当前 openid 写本地 unlock / 映射列。 +""" +from __future__ import annotations + +import time + +from fastapi import APIRouter, Depends, HTTPException, Request +from pydantic import BaseModel, Field + +from ebook_svc.core.deps import get_current_openid +from ebook_svc.services import vip_web_bridge as bridge +from ebook_svc.services.store import store + +router = APIRouter(prefix="/auth", tags=["vip-bridge"]) +VIP_BOOK_ID = "__vip__" + + +class VipWebLoginBody(BaseModel): + email: str | None = Field(default=None, max_length=200) + password: str | None = Field(default=None, max_length=200) + user_id: str | None = Field(default=None, max_length=80) + + +class VipWebBindBody(BaseModel): + email: str = Field(min_length=3, max_length=200) + password: str = Field(min_length=6, max_length=200) + + +def _ensure_bridge_columns() -> None: + """仅 ADD COLUMN,不改既有行。""" + try: + with store.conn() as c: + cols = {r[1] for r in c.execute("PRAGMA table_info(users)").fetchall()} + for name, sql in ( + ("vip_email", "ALTER TABLE users ADD COLUMN vip_email TEXT"), + ("web_user_id", "ALTER TABLE users ADD COLUMN web_user_id TEXT"), + ("vip_email_bound_at", "ALTER TABLE users ADD COLUMN vip_email_bound_at REAL"), + ): + if name not in cols: + c.execute(sql) + except Exception: + pass + + +def _ensure_web_user_id(openid: str, web_user_id: str) -> str: + _ensure_bridge_columns() + if hasattr(store, "ensure_web_user_id"): + return store.ensure_web_user_id(openid, web_user_id) + user = store.get_user(openid) or {} + existing = (user.get("web_user_id") or "").strip() + if existing: + return existing + with store.conn() as c: + c.execute( + "UPDATE users SET web_user_id=?, updated_at=? WHERE openid=?", + (web_user_id, time.time(), openid), + ) + return web_user_id + + +def _set_vip_email_bound(openid: str, email: str, web_user_id: str | None = None) -> None: + _ensure_bridge_columns() + if hasattr(store, "set_vip_email_bound"): + store.set_vip_email_bound(openid, email, web_user_id) + return + email = (email or "").strip().lower() + with store.conn() as c: + if web_user_id: + c.execute( + """ + UPDATE users + SET vip_email=?, web_user_id=COALESCE(web_user_id, ?), + vip_email_bound_at=?, updated_at=? + WHERE openid=? + """, + (email, web_user_id, time.time(), time.time(), openid), + ) + else: + c.execute( + """ + UPDATE users + SET vip_email=?, vip_email_bound_at=?, updated_at=? + WHERE openid=? + """, + (email, time.time(), time.time(), openid), + ) + + +@router.get("/vip-bridge-status") +async def vip_bridge_status(openid: str = Depends(get_current_openid)): + _ensure_bridge_columns() + user = store.get_user(openid) or {} + return { + "ok": True, + "bridgeEnabled": bridge.bridge_enabled(), + "isVip": store.is_unlocked(openid, VIP_BOOK_ID), + "vipEmail": (user.get("vip_email") or "").strip() or None, + "webUserId": (user.get("web_user_id") or "").strip() or None, + "vipEmailBound": bool((user.get("vip_email") or "").strip()), + } + + +@router.post("/vip-web-login") +async def vip_web_login( + body: VipWebLoginBody, + request: Request, + openid: str = Depends(get_current_openid), +): + if not bridge.bridge_enabled(): + raise HTTPException(503, "Web 账号打通未开启") + if store.is_blocked(openid): + raise HTTPException(403, "账号不可用") + + email = (body.email or "").strip().lower() + password = (body.password or "").strip() + user_id = (body.user_id or "").strip() + + if email and password: + result = await bridge.check_web_vip_by_email( + email, + password, + user_id=user_id or None, + wechat_userid=openid, + ) + elif user_id: + result = await bridge.check_web_vip_by_user_id(user_id) + else: + raise HTTPException(400, "请填写邮箱密码,或输入会员账号") + + if not result.get("vip"): + raise HTTPException(401, str(result.get("error") or "验证失败")) + + store.grant_unlock(openid, VIP_BOOK_ID, source="web_vip_login") + bound_email = str(result.get("email") or email or "").strip().lower() + web_uid = ( + (result.get("anonymousUserId") or result.get("effectiveUserId") or user_id or "") + or bridge.openid_to_web_user_id(openid) + ) + try: + _ensure_web_user_id(openid, str(web_uid)) + if bound_email: + _set_vip_email_bound(openid, bound_email, str(web_uid)) + except Exception: + pass + + return { + "ok": True, + "isVip": True, + "email": bound_email or None, + "source": "web_vip_login", + } + + +@router.post("/vip-bind-email") +async def vip_bind_email( + body: VipWebBindBody, + request: Request, + openid: str = Depends(get_current_openid), +): + if not bridge.bridge_enabled(): + raise HTTPException(503, "Web 账号打通未开启") + if store.is_blocked(openid): + raise HTTPException(403, "账号不可用") + if not store.is_unlocked(openid, VIP_BOOK_ID): + raise HTTPException(403, "请先开通小程序 VIP 再绑定邮箱") + + _ensure_bridge_columns() + user = store.get_user(openid) or {} + if (user.get("vip_email") or "").strip(): + return { + "ok": True, + "alreadyBound": True, + "email": (user.get("vip_email") or "").strip(), + "isVip": True, + } + + web_uid = _ensure_web_user_id(openid, bridge.openid_to_web_user_id(openid)) + linked = await bridge.link_email_on_web(body.email, body.password, web_uid) + if not linked.get("ok"): + if linked.get("alreadyVip"): + login = await bridge.check_web_vip_by_email( + body.email, body.password, wechat_userid=openid + ) + if login.get("vip"): + store.grant_unlock(openid, VIP_BOOK_ID, source="web_vip_login") + email = str(login.get("email") or body.email).strip().lower() + _set_vip_email_bound(openid, email, web_uid) + return { + "ok": True, + "isVip": True, + "email": email, + "source": "web_vip_login", + "note": "邮箱已是 Web 会员,已打通小程序", + } + raise HTTPException(400, str(linked.get("error") or "绑定失败")) + + email = str(linked.get("email") or body.email).strip().lower() + _set_vip_email_bound(openid, email, web_uid) + return { + "ok": True, + "isVip": True, + "email": email, + "webUserId": web_uid, + "source": "weapp_bind_email", + } diff --git a/apps/api/services/ebook_svc/services/store.py b/apps/api/services/ebook_svc/services/store.py index ea2b152..3d04a4e 100644 --- a/apps/api/services/ebook_svc/services/store.py +++ b/apps/api/services/ebook_svc/services/store.py @@ -99,6 +99,10 @@ class Store: ("pb_record_id", "ALTER TABLE users ADD COLUMN pb_record_id TEXT"), ("created_at", "ALTER TABLE users ADD COLUMN created_at REAL"), ("last_seen_at", "ALTER TABLE users ADD COLUMN last_seen_at REAL"), + # Web VIP 桥接映射(仅新增列,不改既有行数据) + ("vip_email", "ALTER TABLE users ADD COLUMN vip_email TEXT"), + ("web_user_id", "ALTER TABLE users ADD COLUMN web_user_id TEXT"), + ("vip_email_bound_at", "ALTER TABLE users ADD COLUMN vip_email_bound_at REAL"), ] for name, sql in alters: if name not in cols: @@ -408,6 +412,45 @@ class Store: (pb_record_id, time.time(), openid), ) + def ensure_web_user_id(self, openid: str, web_user_id: str) -> str: + """只给当前 openid 写入/保留 web_user_id,不碰其他用户。""" + user = self.get_user(openid) + if not user: + raise ValueError("user not found") + existing = (user.get("web_user_id") or "").strip() + if existing: + return existing + with self.conn() as c: + c.execute( + "UPDATE users SET web_user_id=?, updated_at=? WHERE openid=?", + (web_user_id, time.time(), openid), + ) + return web_user_id + + def set_vip_email_bound(self, openid: str, email: str, web_user_id: str | None = None): + """仅更新当前 openid 的邮箱绑定字段。""" + email = (email or "").strip().lower() + with self.conn() as c: + if web_user_id: + c.execute( + """ + UPDATE users + SET vip_email=?, web_user_id=COALESCE(web_user_id, ?), + vip_email_bound_at=?, updated_at=? + WHERE openid=? + """, + (email, web_user_id, time.time(), time.time(), openid), + ) + else: + c.execute( + """ + UPDATE users + SET vip_email=?, vip_email_bound_at=?, updated_at=? + WHERE openid=? + """, + (email, time.time(), time.time(), openid), + ) + def update_user_admin( self, openid: str, diff --git a/apps/api/services/ebook_svc/services/vip_config.py b/apps/api/services/ebook_svc/services/vip_config.py index 48a86e9..7beb48a 100644 --- a/apps/api/services/ebook_svc/services/vip_config.py +++ b/apps/api/services/ebook_svc/services/vip_config.py @@ -153,6 +153,8 @@ def read_vip_config() -> dict[str, Any]: "vipEnabled": bool(vip_enabled), "gameEnabled": bool(game_enabled), "joinGroupAction": _as_action(flags.get("joinGroupAction"), "popup"), + # Web ↔ 小程序账号打通(默认关;开启不改既有订单/会员行) + "vipWebBridgeEnabled": flags.get("vipWebBridgeEnabled") is True, "vipPriceFen": price, "vipProductId": product_id, "vipCta": cta, @@ -216,6 +218,9 @@ def write_vip_config(patch: dict[str, Any]) -> dict[str, Any]: if "joinGroupAction" in patch: flags["joinGroupAction"] = _as_action(patch["joinGroupAction"], "popup") + if "vipWebBridgeEnabled" in patch and isinstance(patch["vipWebBridgeEnabled"], bool): + flags["vipWebBridgeEnabled"] = bool(patch["vipWebBridgeEnabled"]) + # 主按钮文案统一不含价格;免费=临时放行文案 try: _price = int(copy.get("vipPriceFen") or 0) diff --git a/apps/api/services/ebook_svc/services/vip_content.py b/apps/api/services/ebook_svc/services/vip_content.py index 02b410f..147050c 100644 --- a/apps/api/services/ebook_svc/services/vip_content.py +++ b/apps/api/services/ebook_svc/services/vip_content.py @@ -167,6 +167,41 @@ DEFAULT_VIP_CONTENT: dict[str, Any] = { "ctaSecondary": "已有账号", "ctaHintWeapp": "微信小程序虚拟支付", "ctaHintH5": "浏览器请走门户 /vip 支付", + # 课时页默认不展示资料;按 lessonMaterials[课时key] 单独配置 + "courseMaterialsUrl": "", + "courseMaterialsDesc": "课程配套资料已上传至网盘,报名后可复制链接打开夸克获取", + "lessonMaterials": {}, + "showNetdisk": True, + "netdisk": [ + { + "id": "system-firmware", + "title": "系统固件(镜像/驱动/依赖包)", + "desc": "系统镜像、固件与驱动相关资源,适合装机/刷机/修复。", + "url": "https://pan.quark.cn/s/3c8439859b8b?pwd=PLgV", + "code": "PLgV", + "copyText": ( + "我用夸克网盘给你分享了「r3s-armbian-ubuntu.7z」,点击链接或复制整段内容," + "打开「夸克APP」即可获取。\n/~4adf3Xsf3S~:/\n" + "链接:https://pan.quark.cn/s/3c8439859b8b?pwd=PLgV\n提取码:PLgV" + ), + "enabled": True, + "sort": 0, + }, + { + "id": "software-tools", + "title": "软件工具(常用安装包)", + "desc": "常用软件与安装包合集(例如刷机/写盘/远控/解压等)。", + "url": "https://pan.quark.cn/s/f46a37ac3937?pwd=dLwD", + "code": "dLwD", + "copyText": ( + "我用夸克网盘给你分享了「无人直播助手 1.0.1.exe.zip」,点击链接或复制整段内容," + "打开「夸克APP」即可获取。\n/b43c3XtQ8y:/\n" + "链接:https://pan.quark.cn/s/f46a37ac3937?pwd=dLwD\n提取码:dLwD" + ), + "enabled": True, + "sort": 1, + }, + ], } @@ -178,6 +213,7 @@ _BOOL_KEYS = ( "showCompare", "showFaq", "showCta", + "showNetdisk", "reviewMode", ) @@ -193,6 +229,8 @@ _STR_KEYS = ( "ctaSecondary", "ctaHintWeapp", "ctaHintH5", + "courseMaterialsUrl", + "courseMaterialsDesc", ) @@ -324,6 +362,48 @@ def merge_vip_content(base: dict[str, Any] | None, patch: dict[str, Any] | None) if "ctaChips" in patch and isinstance(patch["ctaChips"], list): out["ctaChips"] = [str(x) for x in patch["ctaChips"] if str(x).strip()] + if "netdisk" in patch and isinstance(patch["netdisk"], list): + rows: list[dict[str, Any]] = [] + for i, item in enumerate(patch["netdisk"]): + if not isinstance(item, dict): + continue + url = str(item.get("url") or "").strip() + if not url: + continue + rows.append( + { + "id": str(item.get("id") or f"netdisk-{i}"), + "title": str(item.get("title") or "网盘资料"), + "desc": str(item.get("desc") or ""), + "url": url, + "code": str(item.get("code") or "").strip() or None, + "copyText": str(item.get("copyText") or "").strip() or None, + "enabled": item.get("enabled") is not False, + "sort": int(item.get("sort") or i), + } + ) + rows.sort(key=lambda x: int(x.get("sort") or 0)) + out["netdisk"] = rows or deepcopy(DEFAULT_VIP_CONTENT.get("netdisk") or []) + elif not out.get("netdisk"): + out["netdisk"] = deepcopy(DEFAULT_VIP_CONTENT.get("netdisk") or []) + + if "lessonMaterials" in patch and isinstance(patch["lessonMaterials"], dict): + rows: dict[str, Any] = {} + for k, v in patch["lessonMaterials"].items(): + if not isinstance(v, dict): + continue + url = str(v.get("url") or "").strip() + if not url: + continue + rows[str(k)] = { + "url": url, + "title": str(v.get("title") or "").strip() or None, + "desc": str(v.get("desc") or "").strip() or None, + } + out["lessonMaterials"] = rows + elif not isinstance(out.get("lessonMaterials"), dict): + out["lessonMaterials"] = {} + return out diff --git a/apps/api/services/ebook_svc/services/vip_web_bridge.py b/apps/api/services/ebook_svc/services/vip_web_bridge.py new file mode 100644 index 0000000..1693044 --- /dev/null +++ b/apps/api/services/ebook_svc/services/vip_web_bridge.py @@ -0,0 +1,197 @@ +"""Web VIP(vip.hackrobot.cn)↔ 微信小程序 VIP 桥接。 + +安全约定(强制): +- 默认只读调用 web:`/api/vip/check-by-email` 校验会员,不改 PB / payments / site_vip。 +- 本机只写当前 openid 的 SQLite unlocks / users 映射列。 +- 「付费后绑邮箱」才调用 web `/api/auth/link-email`;若邮箱已是会员或已绑定他人 → 拒绝,绝不覆盖。 +- 可用 VIP_WEB_BRIDGE_ENABLED=false 一键关闭。 +""" +from __future__ import annotations + +import hashlib +import logging +import re +from typing import Any + +import httpx + +from ebook_svc.config import settings + +log = logging.getLogger("ebook_svc.vip_web_bridge") + +VIP_BOOK_ID = "__vip__" +_EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$") + + +def bridge_enabled() -> bool: + """环境变量或 remote-config flags.vipWebBridgeEnabled;默认关。""" + if bool(getattr(settings, "vip_web_bridge_enabled", False)): + return True + try: + from ebook_svc.services.vip_config import _read_raw + + raw = _read_raw() or {} + flags = raw.get("flags") if isinstance(raw.get("flags"), dict) else {} + return flags.get("vipWebBridgeEnabled") is True + except Exception: + return False + + +def web_api_base() -> str: + return str(getattr(settings, "vip_web_api_base", "") or "https://vip.hackrobot.cn").rstrip( + "/" + ) + + +def is_valid_email(email: str) -> bool: + return bool(_EMAIL_RE.match((email or "").strip().lower())) + + +def openid_to_web_user_id(openid: str) -> str: + """稳定匿名 user_id(符合 web /^user\\d+$/),每个 openid 唯一,不碰他人账号。""" + digest = hashlib.sha256(f"nomadro-weapp:{openid}".encode("utf-8")).hexdigest() + n = int(digest[:15], 16) + return f"user{n}" + + +async def check_web_vip_by_user_id(user_id: str) -> dict[str, Any]: + """只读:按 Web 匿名/会员 user_id 校验 VIP。""" + if not bridge_enabled(): + return {"ok": False, "vip": False, "error": "web_bridge_disabled"} + user_id = (user_id or "").strip() + if not user_id: + return {"ok": False, "vip": False, "error": "请输入账号"} + + url = f"{web_api_base()}/api/vip/check-by-user" + try: + async with httpx.AsyncClient(timeout=20.0) as client: + r = await client.post(url, json={"user_id": user_id}) + data = r.json() if r.content else {} + except Exception as e: + log.warning("check_web_vip_by_user_id network error: %s", e) + return {"ok": False, "vip": False, "error": "web校验暂不可用,请稍后重试"} + + if not isinstance(data, dict): + return {"ok": False, "vip": False, "error": "web校验响应异常"} + vip = data.get("vip") is True + if not vip: + return { + "ok": False, + "vip": False, + "error": str(data.get("error") or "未找到该账号的会员记录,请确认账号正确"), + } + return { + "ok": True, + "vip": True, + "userId": user_id, + "effectiveUserId": data.get("effectiveUserId") or data.get("user_id") or user_id, + "anonymousUserId": data.get("anonymousUserId") or user_id, + } + + +async def check_web_vip_by_email( + email: str, + password: str, + *, + user_id: str | None = None, + wechat_userid: str | None = None, +) -> dict[str, Any]: + """只读:校验 web 会员。不写 PocketBase。""" + if not bridge_enabled(): + return {"ok": False, "vip": False, "error": "web_bridge_disabled"} + email = (email or "").strip().lower() + password = (password or "").strip() + if not is_valid_email(email) or not password: + return {"ok": False, "vip": False, "error": "请填写邮箱和密码"} + + payload: dict[str, Any] = {"email": email, "password": password} + if user_id: + payload["user_id"] = user_id.strip() + if wechat_userid: + payload["wechat_userid"] = wechat_userid.strip() + + url = f"{web_api_base()}/api/vip/check-by-email" + try: + async with httpx.AsyncClient(timeout=20.0) as client: + r = await client.post(url, json=payload) + data = r.json() if r.content else {} + except Exception as e: + log.warning("check_web_vip_by_email network error: %s", e) + return {"ok": False, "vip": False, "error": "web校验暂不可用,请稍后重试"} + + if not isinstance(data, dict): + return {"ok": False, "vip": False, "error": "web校验响应异常"} + + # 只认明确 vip=true,避免误判 + vip = data.get("vip") is True + + if not vip: + return { + "ok": False, + "vip": False, + "error": str(data.get("error") or "邮箱密码错误,或未找到会员记录"), + } + + return { + "ok": True, + "vip": True, + "effectiveUserId": data.get("effectiveUserId") or data.get("effective_user_id"), + "anonymousUserId": data.get("anonymousUserId") or data.get("anonymous_user_id"), + "email": email, + } + + +async def link_email_on_web( + email: str, + password: str, + anonymous_user_id: str, +) -> dict[str, Any]: + """付费后绑定:仅当邮箱尚未成为 web 会员时调用;失败不重试覆盖。""" + if not bridge_enabled(): + return {"ok": False, "error": "web_bridge_disabled"} + email = (email or "").strip().lower() + password = (password or "").strip() + anonymous_user_id = (anonymous_user_id or "").strip() + if not is_valid_email(email) or len(password) < 6: + return {"ok": False, "error": "请填写有效邮箱,密码至少 6 位"} + if not re.match(r"^user\d+$", anonymous_user_id): + return {"ok": False, "error": "内部账号无效"} + + # 先只读探测:邮箱已是会员 → 禁止覆盖,引导走「已有账号登录」 + probe = await check_web_vip_by_email(email, password) + if probe.get("vip"): + return { + "ok": False, + "error": "该邮箱已是 Web 会员,请返回用「已有账号登录」打通小程序", + "alreadyVip": True, + } + + url = f"{web_api_base()}/api/auth/link-email" + try: + async with httpx.AsyncClient(timeout=25.0) as client: + r = await client.post( + url, + json={ + "email": email, + "password": password, + "anonymousUserId": anonymous_user_id, + }, + ) + data = r.json() if r.content else {} + except Exception as e: + log.warning("link_email_on_web network error: %s", e) + return {"ok": False, "error": "绑定服务暂不可用,请稍后重试"} + + if not isinstance(data, dict): + return {"ok": False, "error": "绑定响应异常"} + if r.status_code >= 400 or not data.get("ok"): + return { + "ok": False, + "error": str(data.get("error") or "绑定失败,请确认邮箱未被占用"), + } + return { + "ok": True, + "email": email, + "pbUserId": (data.get("record") or {}).get("id"), + "anonymousUserId": anonymous_user_id, + } diff --git a/apps/miniprogram/h5/src/app.config.ts b/apps/miniprogram/h5/src/app.config.ts index 6aa489d..d7d4db8 100644 --- a/apps/miniprogram/h5/src/app.config.ts +++ b/apps/miniprogram/h5/src/app.config.ts @@ -90,6 +90,11 @@ const weappConfig = { name: 'vip', pages: ['index'], }, + { + root: 'pages/vip-account', + name: 'vip-account', + pages: ['index'], + }, { root: 'pages/vip-course', name: 'vip-course', @@ -160,6 +165,7 @@ const h5Config = { 'pages/destination/index', 'pages/meetups/index', 'pages/vip/index', + 'pages/vip-account/index', 'pages/vip-course/index', 'pages/vip-lesson/index', 'pages/vip-ebook/index', diff --git a/apps/miniprogram/h5/src/components/MiniModuleGate.tsx b/apps/miniprogram/h5/src/components/MiniModuleGate.tsx index 2fa2a3c..109fc66 100644 --- a/apps/miniprogram/h5/src/components/MiniModuleGate.tsx +++ b/apps/miniprogram/h5/src/components/MiniModuleGate.tsx @@ -1,6 +1,7 @@ import { useEffect, useState, type ReactNode } from 'react' import { View, Text } from '@tarojs/components' import { + getCachedRemoteConfig, isModuleEnabled, loadRemoteConfig, subscribeRemoteConfig, @@ -9,7 +10,7 @@ import type { NomadroRemoteConfig } from '@/data/remoteConfig.defaults' type ModuleKey = keyof NomadroRemoteConfig['modules'] -/** 小程序页级模块闸门:配置未确认前不渲染业务,杜绝先闪后关 */ +/** 小程序页级模块闸门:包内缓存立刻判定,禁止空 View 黑屏 */ export function MiniModuleGate({ moduleKey, children, @@ -17,7 +18,9 @@ export function MiniModuleGate({ moduleKey: ModuleKey children: ReactNode }) { - const [enabled, setEnabled] = useState(null) + const [enabled, setEnabled] = useState(() => + isModuleEnabled(getCachedRemoteConfig(), moduleKey), + ) useEffect(() => { let alive = true @@ -26,17 +29,15 @@ export function MiniModuleGate({ setEnabled(isModuleEnabled(cfg, moduleKey)) } const unsub = subscribeRemoteConfig((r) => apply(r.config)) - void loadRemoteConfig(true).then((r) => apply(r.config)) + void loadRemoteConfig(true) + .then((r) => apply(r.config)) + .catch(() => apply(getCachedRemoteConfig())) return () => { alive = false unsub() } }, [moduleKey]) - if (enabled === null) { - return - } - if (!enabled) { return ( diff --git a/apps/miniprogram/h5/src/components/NetdiskShareModal.scss b/apps/miniprogram/h5/src/components/NetdiskShareModal.scss new file mode 100644 index 0000000..fa958d3 --- /dev/null +++ b/apps/miniprogram/h5/src/components/NetdiskShareModal.scss @@ -0,0 +1,164 @@ +/** + * Web 网盘弹窗结构;小程序用 rem 底栏,触控 ≥2.75rem。 + */ + +.nd-shareMask { + position: fixed; + inset: 0; + z-index: 1300; + display: flex; + align-items: flex-end; + justify-content: center; + padding: 0; + box-sizing: border-box; +} + +.nd-shareBackdrop { + position: absolute; + inset: 0; + background: rgba(0, 0, 0, 0.58); +} + +.nd-sharePanel { + position: relative; + z-index: 1; + width: 100%; + max-height: 82vh; + border-radius: 1.25rem 1.25rem 0 0; + border: 1px solid rgba(255, 255, 255, 0.08); + border-bottom: none; + background: rgba(17, 24, 39, 0.98); + padding: 0.75rem 1.25rem calc(1.25rem + env(safe-area-inset-bottom, 0px)); + box-shadow: 0 -12px 40px rgba(0, 0, 0, 0.4); + box-sizing: border-box; + display: flex; + flex-direction: column; +} + +.nd-shareHandle { + width: 2.25rem; + height: 0.25rem; + border-radius: 99px; + background: rgba(255, 255, 255, 0.2); + margin: 0.15rem auto 0.85rem; +} + +.nd-shareHead { + display: flex; + align-items: center; + justify-content: space-between; + gap: 0.75rem; + margin-bottom: 0.65rem; + min-height: 2.75rem; +} + +.nd-shareTitleRow { + display: flex; + align-items: center; + gap: 0.65rem; + min-width: 0; + flex: 1; +} + +.nd-shareIcon { + font-size: 1.35rem; + line-height: 1; + flex-shrink: 0; +} + +.nd-shareTitle { + font-size: 1.15rem; + font-weight: 700; + color: #f1f5f9; + letter-spacing: -0.02em; + line-height: 1.3; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.nd-shareClose { + width: 2.75rem; + height: 2.75rem; + border-radius: 0.75rem; + display: flex; + align-items: center; + justify-content: center; + color: #94a3b8; + flex-shrink: 0; + border: 1px solid rgba(255, 255, 255, 0.1); +} + +.nd-shareClose:active { + background: rgba(255, 255, 255, 0.08); + color: #f1f5f9; +} + +.nd-shareCloseX { + font-size: 1.05rem; + line-height: 1; +} + +.nd-shareDesc { + display: block; + font-size: 0.9rem; + color: #94a3b8; + line-height: 1.45; + margin-bottom: 0.75rem; +} + +.nd-shareBody { + flex: 1; + max-height: 42vh; + margin-bottom: 1rem; +} + +.nd-sharePre { + display: block; + font-size: 0.88rem; + line-height: 1.55; + color: #e2e8f0; + background: rgba(15, 23, 42, 0.9); + border: 1px solid rgba(255, 255, 255, 0.1); + border-radius: 0.9rem; + padding: 0.9rem 1rem; + white-space: pre-wrap; + word-break: break-word; +} + +.nd-shareActions { + display: flex; + gap: 0.75rem; + align-items: stretch; +} + +.nd-shareBtn { + flex: 1; + min-height: 2.75rem; + border-radius: 0.9rem; + display: flex; + align-items: center; + justify-content: center; + font-size: 1rem; + font-weight: 650; +} + +.nd-shareBtn--ghost { + border: 1px solid rgba(255, 255, 255, 0.14); + background: rgba(30, 41, 59, 0.9); + color: #e2e8f0; +} + +.nd-shareBtn--ghost:active { + background: rgba(51, 65, 85, 0.95); +} + +.nd-shareBtn--primary { + border: 1px solid rgba(245, 158, 11, 0.45); + background: #f59e0b; + color: #0c0c0f; +} + +.nd-shareBtn--primary:active { + opacity: 0.92; +} diff --git a/apps/miniprogram/h5/src/components/NetdiskShareModal.tsx b/apps/miniprogram/h5/src/components/NetdiskShareModal.tsx new file mode 100644 index 0000000..0bcec69 --- /dev/null +++ b/apps/miniprogram/h5/src/components/NetdiskShareModal.tsx @@ -0,0 +1,76 @@ +/** + * Web NetdiskDownloadsSection 弹窗结构参考; + * 尺寸按小程序:rem + 全宽底栏 sheet(勿抄 Web 居中小卡)。 + */ +import { View, Text, ScrollView } from '@tarojs/components' +import Taro from '@tarojs/taro' +import type { VipNetdiskItem } from '../data/vipContent' +import './NetdiskShareModal.scss' + +export function buildNetdiskCopyText(item: VipNetdiskItem): string { + if (item.copyText?.trim()) return item.copyText.trim() + return [item.title, item.url, item.code ? `提取码: ${item.code}` : ''] + .filter(Boolean) + .join('\n') +} + +type Props = { + item: VipNetdiskItem | null + onClose: () => void +} + +export function NetdiskShareModal({ item, onClose }: Props) { + if (!item) return null + + const current: VipNetdiskItem = item + const text = buildNetdiskCopyText(current) + + const onCopy = () => { + void Taro.setClipboardData({ data: text }).then(() => { + Taro.showToast({ title: '已复制,打开夸克即可获取', icon: 'none', duration: 2200 }) + }) + } + + const onCopyUrlOnly = () => { + const url = String(current.url || '').trim() + if (!url) return + void Taro.setClipboardData({ data: url }).then(() => { + Taro.showToast({ title: '链接已复制', icon: 'none' }) + }) + } + + return ( + + + + + + + 📥 + {current.title} + + + ✕ + + + + {current.desc ? {current.desc} : null} + + + + {text} + + + + + + 复制链接 + + + 复制全部 + + + + + ) +} diff --git a/apps/miniprogram/h5/src/components/VipLoginModal.scss b/apps/miniprogram/h5/src/components/VipLoginModal.scss new file mode 100644 index 0000000..80d1203 --- /dev/null +++ b/apps/miniprogram/h5/src/components/VipLoginModal.scss @@ -0,0 +1,227 @@ +/** + * Web LoginModal 结构参考;尺寸按微信小程序触控适配。 + * 注意:weapp designWidth=750 时裸写 px 会被压成 rpx → 弹窗缩成一团, + * 统一用 rem(与 vip-landing 一致),手机全宽底栏,触控 ≥44px。 + */ + +.vip-loginMask { + position: fixed; + inset: 0; + z-index: 1200; + display: flex; + align-items: flex-end; + justify-content: center; + padding: 0; + box-sizing: border-box; +} + +.vip-loginBackdrop { + position: absolute; + inset: 0; + background: rgba(0, 0, 0, 0.6); +} + +.vip-loginPanel { + position: relative; + z-index: 1; + width: 100%; + max-width: none; + border-radius: 1.25rem 1.25rem 0 0; + border: 1px solid rgba(255, 255, 255, 0.08); + border-bottom: none; + background: rgba(17, 24, 39, 0.98); + padding: 0.75rem 1.25rem calc(1.25rem + env(safe-area-inset-bottom, 0px)); + box-shadow: 0 -12px 40px rgba(0, 0, 0, 0.4); + box-sizing: border-box; +} + +.vip-loginHandle { + width: 2.25rem; + height: 0.25rem; + border-radius: 99px; + background: rgba(255, 255, 255, 0.2); + margin: 0.15rem auto 1rem; +} + +.vip-loginHead { + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: 1.1rem; + min-height: 2.75rem; +} + +.vip-loginTitle { + font-size: 1.5rem; + font-weight: 700; + color: #f1f5f9; + letter-spacing: -0.02em; + line-height: 1.25; +} + +.vip-loginClose { + width: 2.75rem; + height: 2.75rem; + border-radius: 0.65rem; + display: flex; + align-items: center; + justify-content: center; + color: #94a3b8; + flex-shrink: 0; +} + +.vip-loginClose:active { + background: rgba(255, 255, 255, 0.08); + color: #f1f5f9; +} + +.vip-loginCloseX { + font-size: 1.15rem; + line-height: 1; +} + +.vip-loginTabs { + display: flex; + gap: 0.65rem; + margin-bottom: 1rem; +} + +.vip-loginTab { + flex: 1; + text-align: center; + min-height: 2.75rem; + padding: 0.75rem 0.5rem; + box-sizing: border-box; + display: flex; + align-items: center; + justify-content: center; + border-radius: 0.65rem; + font-size: 0.95rem; + font-weight: 500; + color: #94a3b8; + background: rgba(255, 255, 255, 0.05); +} + +.vip-loginTab.is-on { + color: #1c1917; + background: #f59e0b; + font-weight: 600; +} + +.vip-loginInput { + width: 100%; + box-sizing: border-box; + height: 3rem; + min-height: 3rem; + padding: 0 1rem; + margin-bottom: 0.85rem; + border-radius: 0.65rem; + border: 1px solid rgba(255, 255, 255, 0.1); + background: #0a0e17; + color: #f1f5f9; + font-size: 1rem; + line-height: 3rem; +} + +.vip-loginErr { + display: block; + font-size: 0.875rem; + color: #ef4444; + margin: -0.35rem 0 0.85rem; + line-height: 1.4; +} + +.vip-loginBtn { + width: 100%; + height: 3.15rem; + min-height: 3.15rem; + line-height: 3.15rem; + padding: 0; + border-radius: 0.75rem; + border: none; + background: #f59e0b; + color: #1c1917; + font-size: 1.05rem; + font-weight: 700; +} + +.vip-loginBtn::after { + border: none; +} + +.vip-loginBtn[disabled] { + opacity: 0.55; +} + +.vip-loginSkip { + margin-top: 0.85rem; + text-align: center; + font-size: 0.9rem; + color: #64748b; + padding: 0.75rem; + min-height: 2.75rem; + box-sizing: border-box; +} + +.vip-loginBoot { + position: absolute; + inset: 0; + z-index: 5; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 0.5rem; + background: rgba(10, 14, 23, 0.92); +} + +.vip-loginBootRing { + position: relative; + width: 5rem; + height: 5rem; + display: flex; + align-items: center; + justify-content: center; + margin-bottom: 0.75rem; +} + +.vip-loginBootRingOuter { + position: absolute; + inset: 0; + border-radius: 50%; + border: 2px solid rgba(245, 158, 11, 0.2); + border-top-color: #f59e0b; + animation: vipLoginSpin 1.05s linear infinite; +} + +.vip-loginBootRingInner { + position: absolute; + inset: 0.5rem; + border-radius: 50%; + border: 2px solid transparent; + border-bottom-color: rgba(251, 191, 36, 0.45); + animation: vipLoginSpin 0.75s linear infinite reverse; +} + +.vip-loginBootEmoji { + font-size: 1.75rem; + z-index: 1; +} + +.vip-loginBootTitle { + font-size: 1rem; + font-weight: 600; + color: #f1f5f9; + letter-spacing: 0.04em; +} + +.vip-loginBootSub { + font-size: 0.875rem; + color: #94a3b8; +} + +@keyframes vipLoginSpin { + to { + transform: rotate(360deg); + } +} diff --git a/apps/miniprogram/h5/src/components/VipLoginModal.tsx b/apps/miniprogram/h5/src/components/VipLoginModal.tsx new file mode 100644 index 0000000..02a0c67 --- /dev/null +++ b/apps/miniprogram/h5/src/components/VipLoginModal.tsx @@ -0,0 +1,224 @@ +/** + * 结构参考 Web VIP LoginModal(标题 / 账号·邮箱 / 输入 / 验证) + * 尺寸按微信小程序:全宽底栏 + rem 触控区(勿裸写 px,designWidth=750 会缩没) + */ +import { View, Text, Input, Button } from '@tarojs/components' +import { useEffect, useState } from 'react' +import { bindVipEmailAccount, loginWebVipAccount } from '../utils/vipWebAccount' +import './VipLoginModal.scss' + +type Mode = 'login' | 'bind' +type Tab = 'user_id' | 'email' + +type Props = { + open: boolean + mode?: Mode + allowSkip?: boolean + brand?: string + onClose: () => void + onSuccess: () => void +} + +function friendlyErr(raw: unknown): string { + const msg = raw instanceof Error ? raw.message : String(raw || '') + if (/打通未开启|web_bridge_disabled|503/i.test(msg)) { + return '账号打通暂未开放,请稍后再试' + } + if (/需要登录|未登录/i.test(msg)) { + return '请先完成微信登录后再试' + } + return msg || '验证失败,请稍后重试' +} + +export function VipLoginModal({ + open, + mode = 'login', + allowSkip = false, + onClose, + onSuccess, +}: Props) { + const [tab, setTab] = useState('user_id') + const [userId, setUserId] = useState('') + const [email, setEmail] = useState('') + const [password, setPassword] = useState('') + const [error, setError] = useState(null) + const [loading, setLoading] = useState(false) + + useEffect(() => { + if (!open) { + setError(null) + setLoading(false) + return + } + setTab(mode === 'bind' ? 'email' : 'user_id') + setError(null) + setUserId('') + setEmail('') + setPassword('') + setLoading(false) + }, [open, mode]) + + if (!open) return null + + const title = mode === 'bind' ? '绑定邮箱' : '登录' + + async function submit() { + if (loading) return + setError(null) + + if (mode === 'bind' || tab === 'email') { + const em = email.trim() + const pw = password.trim() + if (!em) { + setError('请输入邮箱') + return + } + if (!pw) { + setError('请输入密码') + return + } + if (mode === 'bind' && pw.length < 6) { + setError('密码至少 6 位') + return + } + setLoading(true) + try { + if (mode === 'bind') { + await bindVipEmailAccount({ email: em, password: pw }) + } else { + await loginWebVipAccount({ email: em, password: pw }) + } + onSuccess() + } catch (e) { + setError(friendlyErr(e)) + setLoading(false) + } + return + } + + const uid = userId.trim() + if (!uid) { + setError('请输入您的账号') + return + } + setLoading(true) + try { + await loginWebVipAccount({ userId: uid }) + onSuccess() + } catch (e) { + setError(friendlyErr(e) || '未找到该账号的会员记录,请确认账号正确') + setLoading(false) + } + } + + return ( + + + + e.stopPropagation()}> + + + {title} + + ✕ + + + + {mode === 'login' ? ( + + { + if (loading) return + setTab('user_id') + setError(null) + }} + > + 账号 + + { + if (loading) return + setTab('email') + setError(null) + }} + > + 邮箱 + + + ) : null} + + {mode === 'login' && tab === 'user_id' ? ( + <> + setUserId(e.detail.value)} + onConfirm={() => void submit()} + /> + {error ? {error} : null} + + + ) : ( + <> + setEmail(e.detail.value)} + /> + setPassword(e.detail.value)} + onConfirm={() => void submit()} + /> + {error ? {error} : null} + + {mode === 'bind' && allowSkip ? ( + + 稍后再说 + + ) : null} + + )} + + + {loading ? ( + + + + + 🌍 + + 异度星球 + + {mode === 'bind' ? '正在绑定邮箱…' : '正在验证并登录…'} + + + ) : null} + + ) +} diff --git a/apps/miniprogram/h5/src/data/remoteConfig.defaults.ts b/apps/miniprogram/h5/src/data/remoteConfig.defaults.ts index 5b58a35..ed784fe 100644 --- a/apps/miniprogram/h5/src/data/remoteConfig.defaults.ts +++ b/apps/miniprogram/h5/src/data/remoteConfig.defaults.ts @@ -70,6 +70,8 @@ export type NomadroRemoteConfig = { offlineBadge: boolean /** VIP 知识社群:未付费可进列表试读(与 memo_settings.allowTrialBrowse 对齐意图) */ memoTrialBrowse?: boolean + /** Web VIP ↔ 小程序账号打通;默认关,后台可开(仅增量 flag) */ + vipWebBridgeEnabled?: boolean } copy: { homeBrand: string @@ -176,6 +178,7 @@ export const DEFAULT_REMOTE_CONFIG: NomadroRemoteConfig = { joinGroupAction: 'popup', offlineBadge: false, memoTrialBrowse: true, + vipWebBridgeEnabled: false, }, copy: { homeBrand: 'nomadro', diff --git a/apps/miniprogram/h5/src/data/vipContent.ts b/apps/miniprogram/h5/src/data/vipContent.ts index 8366f10..3688318 100644 --- a/apps/miniprogram/h5/src/data/vipContent.ts +++ b/apps/miniprogram/h5/src/data/vipContent.ts @@ -47,6 +47,17 @@ export type VipFaqItem = { a: string } +export type VipNetdiskItem = { + id: string + title: string + desc: string + url: string + code?: string + copyText?: string + enabled?: boolean + sort?: number +} + export type WeappVipContent = { heroEyebrow: string heroTitleAccent: string @@ -79,6 +90,23 @@ export type WeappVipContent = { ctaSecondary: string ctaHintWeapp: string ctaHintH5: string + /** + * 全局课时资料(极少用)。课时页优先读 lessonMaterials[lessonKey]; + * 都空则该视频页不展示资料模块。 + */ + courseMaterialsUrl: string + courseMaterialsDesc: string + /** 按课时 key(如 0-0)单独配置资料链接;未配置的课时不展示 */ + lessonMaterials: Record + /** 对齐 Web VIP 落地「网盘下载」(仅落地页,不进课时页) */ + showNetdisk: boolean + netdisk: VipNetdiskItem[] +} + +export type VipLessonMaterial = { + url: string + title?: string + desc?: string } export const DEFAULT_WEAPP_VIP: WeappVipContent = { @@ -217,9 +245,38 @@ export const DEFAULT_WEAPP_VIP: WeappVipContent = { }, ], ctaChips: ['阶梯定价', '数字交付', '持续更新', '不支持退款'], - ctaSecondary: '已有账号', + ctaSecondary: '已有账号登录', ctaHintWeapp: '微信小程序虚拟支付', ctaHintH5: '浏览器请走门户 /vip 支付', + // 课时页默认不展示;仅 lessonMaterials / 运营显式配置才出现 + courseMaterialsUrl: '', + courseMaterialsDesc: '课程配套资料已上传至网盘,报名后可复制链接打开夸克获取', + lessonMaterials: {}, + showNetdisk: true, + netdisk: [ + { + id: 'system-firmware', + title: '系统固件(镜像/驱动/依赖包)', + desc: '系统镜像、固件与驱动相关资源,适合装机/刷机/修复。', + url: 'https://pan.quark.cn/s/3c8439859b8b?pwd=PLgV', + code: 'PLgV', + copyText: + '我用夸克网盘给你分享了「r3s-armbian-ubuntu.7z」,点击链接或复制整段内容,打开「夸克APP」即可获取。\n/~4adf3Xsf3S~:/\n链接:https://pan.quark.cn/s/3c8439859b8b?pwd=PLgV\n提取码:PLgV', + enabled: true, + sort: 0, + }, + { + id: 'software-tools', + title: '软件工具(常用安装包)', + desc: '常用软件与安装包合集(例如刷机/写盘/远控/解压等)。', + url: 'https://pan.quark.cn/s/f46a37ac3937?pwd=dLwD', + code: 'dLwD', + copyText: + '我用夸克网盘给你分享了「无人直播助手 1.0.1.exe.zip」,点击链接或复制整段内容,打开「夸克APP」即可获取。\n/b43c3XtQ8y:/\n链接:https://pan.quark.cn/s/f46a37ac3937?pwd=dLwD\n提取码:dLwD', + enabled: true, + sort: 1, + }, + ], } function mergeList( @@ -284,6 +341,8 @@ export function mergeWeappVipContent( showCompare: typeof partial.showCompare === 'boolean' ? partial.showCompare : base.showCompare, showFaq: typeof partial.showFaq === 'boolean' ? partial.showFaq : base.showFaq, showCta: typeof partial.showCta === 'boolean' ? partial.showCta : base.showCta, + showNetdisk: + typeof partial.showNetdisk === 'boolean' ? partial.showNetdisk : base.showNetdisk, reviewMode: typeof partial.reviewMode === 'boolean' ? partial.reviewMode : base.reviewMode, stats: { ...base.stats, ...(partial.stats || {}) }, topics: mergeList(base.topics, partial.topics ?? base.topics), @@ -292,9 +351,85 @@ export function mergeWeappVipContent( compare: Array.isArray(partial.compare) ? partial.compare : base.compare, faq: Array.isArray(partial.faq) ? partial.faq : base.faq, ctaChips: Array.isArray(partial.ctaChips) ? partial.ctaChips.map(String) : base.ctaChips, + courseMaterialsUrl: + typeof partial.courseMaterialsUrl === 'string' + ? partial.courseMaterialsUrl.trim() + : base.courseMaterialsUrl, + courseMaterialsDesc: + typeof partial.courseMaterialsDesc === 'string' && partial.courseMaterialsDesc.trim() + ? partial.courseMaterialsDesc + : base.courseMaterialsDesc, + lessonMaterials: mergeLessonMaterials( + base.lessonMaterials, + partial.lessonMaterials as Record | undefined, + ), + netdisk: ensureNetdisk( + Array.isArray(partial.netdisk) ? (partial.netdisk as VipNetdiskItem[]) : base.netdisk, + ), } } +function mergeLessonMaterials( + base: Record, + patch?: Record | null, +): Record { + const out: Record = { ...(base || {}) } + if (!patch || typeof patch !== 'object') return out + for (const [key, row] of Object.entries(patch)) { + if (!row || typeof row !== 'object') continue + const url = String(row.url || '').trim() + if (!url) { + delete out[key] + continue + } + out[key] = { + url, + title: row.title ? String(row.title) : undefined, + desc: row.desc ? String(row.desc) : undefined, + } + } + return out +} + +/** 课时页:仅当该 key 单独配置了 url 才返回;不回退全局网盘列表 */ +export function resolveLessonMaterials( + config: ConfigWithWeapp | null | undefined, + lessonKey: string, +): VipLessonMaterial | null { + const vip = resolveWeappVipContent(config) + const key = String(lessonKey || '').trim() + if (!key) return null + const hit = vip.lessonMaterials?.[key] + const url = String(hit?.url || '').trim() + if (url) { + return { + url, + title: hit?.title || '课程资料下载', + desc: hit?.desc || vip.courseMaterialsDesc, + } + } + return null +} + +function ensureNetdisk(items: VipNetdiskItem[]): VipNetdiskItem[] { + const cleaned = (items || []) + .filter((x) => x && typeof x === 'object' && String(x.url || '').trim()) + .map((x, i) => ({ + ...x, + id: String(x.id || `netdisk-${i}`), + title: String(x.title || '网盘资料'), + desc: String(x.desc || ''), + url: String(x.url || '').trim(), + code: x.code ? String(x.code) : undefined, + copyText: x.copyText ? String(x.copyText) : undefined, + enabled: x.enabled !== false, + sort: typeof x.sort === 'number' ? x.sort : i, + })) + .sort((a, b) => Number(a.sort || 0) - Number(b.sort || 0)) + if (cleaned.length) return cleaned + return DEFAULT_WEAPP_VIP.netdisk.map((x) => ({ ...x })) +} + export type ConfigWithWeapp = { platforms?: { weapp?: { diff --git a/apps/miniprogram/h5/src/data/vipCourse.ts b/apps/miniprogram/h5/src/data/vipCourse.ts index fd0af7c..c1c4e9a 100644 --- a/apps/miniprogram/h5/src/data/vipCourse.ts +++ b/apps/miniprogram/h5/src/data/vipCourse.ts @@ -25,8 +25,35 @@ const V: Record = { '2-2': 'https://minioweb.hackrobot.cn/hackrobot/8. tiktok直播_20260326_095441_1064.mp4', '2-3': 'https://minioweb.hackrobot.cn/hackrobot/9. tiktok直播-2_20260326_095403_943.mp4', } -const FALLBACK = - 'https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4' +/** 无正式片源时留空,避免国内微信卡在 Google 示例片 */ +const FALLBACK = '' + +/** 网盘/对象存储路径常含空格与中文;微信 Video 需编码后才能播 */ +export function encodeVideoSrc(url: string): string { + const raw = String(url || '').trim() + if (!raw) return '' + try { + const u = new URL(raw) + u.pathname = u.pathname + .split('/') + .map((seg) => { + if (!seg) return seg + try { + return encodeURIComponent(decodeURIComponent(seg)) + } catch { + return encodeURIComponent(seg) + } + }) + .join('/') + return u.toString() + } catch { + try { + return encodeURI(raw) + } catch { + return raw + } + } +} const RAW = [ { diff --git a/apps/miniprogram/h5/src/pages/mine/index.tsx b/apps/miniprogram/h5/src/pages/mine/index.tsx index b6b7cf9..aade112 100644 --- a/apps/miniprogram/h5/src/pages/mine/index.tsx +++ b/apps/miniprogram/h5/src/pages/mine/index.tsx @@ -87,7 +87,10 @@ function MinePage() { Taro.showToast({ title: '登录成功', icon: 'success' }) } catch (e) { const msg = e instanceof Error ? e.message : '登录失败' - Taro.showToast({ title: msg.slice(0, 40), icon: 'none' }) + // 拉黑已由 request 弹 Modal「账号不可用」,此处勿再 toast 重复 + if (msg !== '账号不可用') { + Taro.showToast({ title: msg.slice(0, 40), icon: 'none' }) + } } finally { setLoading(false) } diff --git a/apps/miniprogram/h5/src/pages/vip-account/index.config.ts b/apps/miniprogram/h5/src/pages/vip-account/index.config.ts new file mode 100644 index 0000000..57af18d --- /dev/null +++ b/apps/miniprogram/h5/src/pages/vip-account/index.config.ts @@ -0,0 +1,7 @@ +export default definePageConfig({ + navigationStyle: 'custom', + navigationBarTitleText: '会员账号', + navigationBarBackgroundColor: '#0c0c0f', + navigationBarTextStyle: 'white', + backgroundColor: '#0c0c0f', +}) diff --git a/apps/miniprogram/h5/src/pages/vip-account/index.scss b/apps/miniprogram/h5/src/pages/vip-account/index.scss new file mode 100644 index 0000000..2e75a1f --- /dev/null +++ b/apps/miniprogram/h5/src/pages/vip-account/index.scss @@ -0,0 +1,279 @@ +/* 对齐 VIP 落地:深色科技 + 琥珀强调,一屏一构图 */ + +.vip-acc { + --va-bg: #0a0e17; + --va-fg: #f1f5f9; + --va-muted: #94a3b8; + --va-accent: #f59e0b; + --va-border: rgba(255, 255, 255, 0.1); + position: relative; + min-height: 100vh; + background: var(--va-bg); + color: var(--va-fg); + overflow: hidden; + box-sizing: border-box; + font-family: 'Outfit', 'PingFang SC', 'Microsoft YaHei', sans-serif; +} + +.vip-acc-bg { + position: absolute; + inset: 0; + pointer-events: none; + z-index: 0; +} + +.vip-acc-orb { + position: absolute; + border-radius: 50%; + filter: blur(48px); + opacity: 0.45; + animation: vipAccFloat 12s ease-in-out infinite; +} + +.vip-acc-orb:nth-child(1) { + width: 220px; + height: 220px; + top: -60px; + right: -40px; + background: radial-gradient(circle, rgba(245, 158, 11, 0.55), transparent 70%); +} + +.vip-acc-orb:nth-child(2) { + width: 180px; + height: 180px; + bottom: 12%; + left: -50px; + background: radial-gradient(circle, rgba(78, 205, 196, 0.35), transparent 70%); + animation-delay: -4s; +} + +.vip-acc-orb:nth-child(3) { + width: 140px; + height: 140px; + top: 42%; + right: 8%; + background: radial-gradient(circle, rgba(255, 107, 107, 0.28), transparent 70%); + animation-delay: -7s; +} + +.vip-acc-mesh { + position: absolute; + inset: 0; + background-image: linear-gradient(rgba(255, 255, 255, 0.03) 1px, transparent 1px), + linear-gradient(90deg, rgba(255, 255, 255, 0.03) 1px, transparent 1px); + background-size: 48px 48px; + mask-image: radial-gradient(ellipse at 50% 30%, black 20%, transparent 75%); +} + +@keyframes vipAccFloat { + 0%, + 100% { + transform: translate3d(0, 0, 0) scale(1); + } + 50% { + transform: translate3d(0, 18px, 0) scale(1.06); + } +} + +.vip-acc-inner { + position: relative; + z-index: 1; + padding: 0 20px 40px; + max-width: 440px; + margin: 0 auto; +} + +.vip-acc-top { + display: flex; + align-items: center; + justify-content: space-between; + padding-top: calc(var(--safe-header, 88px) + 4px); + margin-bottom: 28px; +} + +.vip-acc-back { + min-width: 44px; + min-height: 44px; + border-radius: 14px; + background: rgba(255, 255, 255, 0.06); + border: 1px solid var(--va-border); + display: flex; + align-items: center; + justify-content: center; + font-size: 18px; + color: var(--va-fg); +} + +.vip-acc-brand { + font-size: 13px; + font-weight: 700; + letter-spacing: 0.08em; + text-transform: uppercase; + color: var(--va-muted); +} + +.vip-acc-brand em { + font-style: normal; + color: var(--va-accent); +} + +.vip-acc-hero { + margin-bottom: 22px; +} + +.vip-acc-kicker { + display: inline-block; + font-size: 11px; + font-weight: 600; + letter-spacing: 0.12em; + text-transform: uppercase; + color: var(--va-accent); + margin-bottom: 10px; +} + +.vip-acc-h1 { + display: block; + font-size: 28px; + line-height: 1.2; + font-weight: 800; + letter-spacing: -0.03em; + margin-bottom: 10px; +} + +.vip-acc-lead { + display: block; + font-size: 14px; + line-height: 1.65; + color: var(--va-muted); +} + +.vip-acc-card { + background: rgba(17, 24, 39, 0.72); + border: 1px solid var(--va-border); + border-radius: 22px; + padding: 22px 18px 20px; + backdrop-filter: blur(18px); + box-shadow: 0 24px 60px rgba(0, 0, 0, 0.35); +} + +.vip-acc-tabs { + display: flex; + gap: 8px; + margin-bottom: 20px; + padding: 4px; + border-radius: 14px; + background: rgba(255, 255, 255, 0.04); +} + +.vip-acc-tab { + flex: 1; + text-align: center; + padding: 10px 8px; + border-radius: 11px; + font-size: 13px; + font-weight: 600; + color: var(--va-muted); +} + +.vip-acc-tab.is-on { + color: #0c0c0f; + background: linear-gradient(135deg, #fbbf24, #f59e0b); +} + +.vip-acc-field { + margin-bottom: 14px; +} + +.vip-acc-label { + display: block; + font-size: 12px; + font-weight: 600; + color: rgba(241, 245, 249, 0.55); + margin-bottom: 8px; +} + +.vip-acc-input { + width: 100%; + box-sizing: border-box; + height: 48px; + padding: 0 16px; + border-radius: 14px; + background: rgba(255, 255, 255, 0.05); + border: 1px solid rgba(255, 255, 255, 0.12); + color: var(--va-fg); + font-size: 16px; +} + +.vip-acc-input:focus { + border-color: rgba(245, 158, 11, 0.65); + background: rgba(245, 158, 11, 0.06); +} + +.vip-acc-btn { + margin-top: 6px; + width: 100%; + height: 52px; + line-height: 52px; + border-radius: 16px; + border: none; + background: linear-gradient(135deg, #fbbf24 0%, #f59e0b 50%, #d97706 100%); + color: #1c1917; + font-size: 16px; + font-weight: 800; + letter-spacing: 0.02em; + box-shadow: 0 12px 32px rgba(245, 158, 11, 0.28); +} + +.vip-acc-btn::after { + border: none; +} + +.vip-acc-btn[disabled] { + opacity: 0.45; + box-shadow: none; +} + +.vip-acc-btn-ghost { + margin-top: 12px; + width: 100%; + height: 44px; + line-height: 44px; + border-radius: 14px; + background: transparent; + border: 1px solid var(--va-border); + color: var(--va-muted); + font-size: 14px; + font-weight: 600; +} + +.vip-acc-btn-ghost::after { + border: none; +} + +.vip-acc-banner { + margin-bottom: 14px; + padding: 12px 14px; + border-radius: 14px; + font-size: 12px; + line-height: 1.55; +} + +.vip-acc-banner.is-warn { + color: #fbbf24; + background: rgba(245, 158, 11, 0.1); + border: 1px solid rgba(245, 158, 11, 0.28); +} + +.vip-acc-banner.is-ok { + color: #5eead4; + background: rgba(78, 205, 196, 0.1); + border: 1px solid rgba(78, 205, 196, 0.28); +} + +.vip-acc-foot { + margin-top: 18px; + text-align: center; + font-size: 11px; + line-height: 1.6; + color: rgba(148, 163, 184, 0.75); +} diff --git a/apps/miniprogram/h5/src/pages/vip-account/index.tsx b/apps/miniprogram/h5/src/pages/vip-account/index.tsx new file mode 100644 index 0000000..ba963ca --- /dev/null +++ b/apps/miniprogram/h5/src/pages/vip-account/index.tsx @@ -0,0 +1,236 @@ +/** + * Web ↔ 小程序 VIP 账号(视觉对齐 VIP 落地) + * login:已有 Web VIP · bind:付费后绑邮箱 + */ +import { Input, Button } from '@tarojs/components' +import Taro, { useRouter } from '@tarojs/taro' +import { useEffect, useMemo, useState } from 'react' +import { H5Box, H5Txt } from '../../components/H5Box' +import { getSafeAreaMetrics } from '../../utils/safeArea' +import { + bindVipEmailAccount, + fetchVipBridgeStatus, + loginWebVipAccount, +} from '../../utils/vipWebAccount' +import { goPage } from '../../utils/nav' +import './index.scss' + +type Mode = 'login' | 'bind' + +export default function VipAccountPage() { + const router = useRouter() + const initial: Mode = router.params?.mode === 'bind' ? 'bind' : 'login' + const [mode, setMode] = useState(initial) + const safe = useMemo(() => getSafeAreaMetrics(), []) + const [email, setEmail] = useState('') + const [password, setPassword] = useState('') + const [userId, setUserId] = useState('') + const [showExtra, setShowExtra] = useState(false) + const [busy, setBusy] = useState(false) + const [bridgeOn, setBridgeOn] = useState(null) + const [boundEmail, setBoundEmail] = useState(null) + + useEffect(() => { + setMode(initial) + }, [initial]) + + useEffect(() => { + void (async () => { + try { + const st = await fetchVipBridgeStatus() + setBridgeOn(!!st.bridgeEnabled) + if (st.vipEmail) setBoundEmail(st.vipEmail) + } catch { + setBridgeOn(false) + } + })() + }, [mode]) + + const copy = + mode === 'bind' + ? { + kicker: 'Secure Link', + h1: '绑定邮箱', + lead: '设置邮箱与密码后,可在 Web 会员站用同一账号登录,权益互通。', + cta: '完成绑定', + } + : { + kicker: 'Welcome Back', + h1: '已有账号登录', + lead: '使用 Web 会员邮箱登录,成功后本微信将同步 VIP 权益。', + cta: '登录并同步 VIP', + } + + async function onSubmit() { + if (busy) return + const em = email.trim() + const pw = password.trim() + if (!em || !pw) { + Taro.showToast({ title: '请填写邮箱和密码', icon: 'none' }) + return + } + if (mode === 'bind' && pw.length < 6) { + Taro.showToast({ title: '密码至少 6 位', icon: 'none' }) + return + } + + setBusy(true) + try { + if (mode === 'login') { + const res = await loginWebVipAccount({ + email: em, + password: pw, + userId: userId.trim() || undefined, + }) + if (res.isVip) { + Taro.showToast({ title: 'VIP 已同步', icon: 'success' }) + setTimeout(() => goPage('/pages/vip/index'), 480) + return + } + Taro.showToast({ title: '登录失败', icon: 'none' }) + return + } + + const res = await bindVipEmailAccount({ email: em, password: pw }) + if (res.ok) { + Taro.showToast({ title: res.alreadyBound ? '已绑定' : '绑定成功', icon: 'success' }) + setTimeout(() => goPage('/pages/vip/index'), 480) + return + } + Taro.showToast({ title: '绑定失败', icon: 'none' }) + } catch (e) { + const msg = e instanceof Error ? e.message : String(e) + Taro.showModal({ + title: mode === 'bind' ? '绑定未完成' : '登录未完成', + content: msg.slice(0, 140) || '请稍后重试', + showCancel: false, + }) + } finally { + setBusy(false) + } + } + + function goBack() { + void Taro.navigateBack().catch(() => goPage('/pages/vip/index')) + } + + return ( + + + + + + + + + + + + ← + + + nomadro VIP + + + + + {copy.kicker} + {copy.h1} + {copy.lead} + + + + {initial !== 'bind' ? ( + + setMode('login')} + > + 登录同步 + + setMode('bind')} + > + 绑定邮箱 + + + ) : null} + + {bridgeOn === false ? ( + + 账号打通暂未开启。请在管理后台打开「Web 账号打通」后再试;开启前不影响现有会员。 + + ) : null} + + {boundEmail ? ( + 已绑定 {boundEmail} + ) : null} + + + 邮箱 + setEmail(e.detail.value)} + /> + + + + 密码 + setPassword(e.detail.value)} + /> + + + {mode === 'login' && showExtra ? ( + + 历史账号 ID(可选) + setUserId(e.detail.value)} + /> + + ) : null} + + + + {mode === 'login' ? ( + + ) : ( + + )} + + + + 仅同步当前微信账号 · 不覆盖他人会员数据 + {'\n'} + Web:vip.hackrobot.cn + + + + ) +} diff --git a/apps/miniprogram/h5/src/pages/vip-course/index.tsx b/apps/miniprogram/h5/src/pages/vip-course/index.tsx index 7728ff7..68c03db 100644 --- a/apps/miniprogram/h5/src/pages/vip-course/index.tsx +++ b/apps/miniprogram/h5/src/pages/vip-course/index.tsx @@ -22,7 +22,12 @@ import { CLOUDPHONE_HERO, } from '../../data/vipCloudphoneLanding' import { goPage } from '../../utils/nav' -import { goVipUnlock, resolveVipContentAccess } from '../../utils/vipAccess' +import { + goVipUnlock, + hasVipContentAccessSync, + resolveVipContentAccess, + subscribeVipAccess, +} from '../../utils/vipAccess' import { getLastWatched, getProgress, @@ -102,6 +107,8 @@ export default function VipCoursePage() { setIsVip(ok) setReady(true) })() + const unsub = subscribeVipAccess((vip) => setIsVip(hasVipContentAccessSync(vip))) + return () => unsub() }, [config?.title, isCloudphone]) useEffect(() => { diff --git a/apps/miniprogram/h5/src/pages/vip-ebook/index.tsx b/apps/miniprogram/h5/src/pages/vip-ebook/index.tsx index b1e3272..8131a0a 100644 --- a/apps/miniprogram/h5/src/pages/vip-ebook/index.tsx +++ b/apps/miniprogram/h5/src/pages/vip-ebook/index.tsx @@ -15,7 +15,12 @@ import { } from '../../data/vipEbooks' import { loadVipEbook } from '../../services/vipLibrary' import { goPage } from '../../utils/nav' -import { goVipUnlock, resolveVipContentAccess } from '../../utils/vipAccess' +import { + goVipUnlock, + hasVipContentAccessSync, + resolveVipContentAccess, + subscribeVipAccess, +} from '../../utils/vipAccess' import { getSafeAreaMetrics } from '../../utils/safeArea' import { useNomadroTheme } from '@/utils/h5Theme' import { @@ -160,6 +165,18 @@ export default function VipEbookPage() { }) }, [bookId]) + // 后台开通 VIP:App 级 3s 轮询 → 近实时放行 + useEffect(() => { + return subscribeVipAccess((vip) => { + const pack = VIP_EBOOKS[bookId] + if (pack?.free) { + setAllowed(true) + return + } + setAllowed(hasVipContentAccessSync(vip)) + }) + }, [bookId]) + function onScroll(e: { detail?: { scrollTop?: number; scrollHeight?: number } }) { diff --git a/apps/miniprogram/h5/src/pages/vip-lesson/index.tsx b/apps/miniprogram/h5/src/pages/vip-lesson/index.tsx index 911e3ad..111dfb9 100644 --- a/apps/miniprogram/h5/src/pages/vip-lesson/index.tsx +++ b/apps/miniprogram/h5/src/pages/vip-lesson/index.tsx @@ -7,10 +7,28 @@ import Taro, { useRouter } from '@tarojs/taro' import { useEffect, useMemo, useState } from 'react' import { H5Box, H5Txt } from '../../components/H5Box' import { MarkdownView } from '../../components/MarkdownView' -import { VIP_COURSE_MODULES, type VipLesson, type VipModule } from '../../data/vipCourse' +import { + VIP_COURSE_MODULES, + encodeVideoSrc, + getVipLesson, + type VipLesson, + type VipModule, +} from '../../data/vipCourse' +import { + resolveLessonMaterials, + type VipNetdiskItem, +} from '../../data/vipContent' +import { NetdiskShareModal } from '../../components/NetdiskShareModal' import { loadVipLesson } from '../../services/vipLibrary' +import { getCachedRemoteConfig, loadRemoteConfig } from '../../services/remoteConfig' import { goPage } from '../../utils/nav' -import { goVipUnlock, resolveVipContentAccess } from '../../utils/vipAccess' +import { + goVipUnlock, + hasVipContentAccessSync, + isVipPaidLocal, + resolveVipContentAccess, + subscribeVipAccess, +} from '../../utils/vipAccess' import { getProgress, markCompleted, @@ -33,35 +51,60 @@ function findPrevNext(modules: VipModule[], m: number, l: number) { } } +/** 仅该课时单独配置了资料链接才展示;不套用落地页全局网盘 */ +function materialsForLesson(lessonKey: string): { + items: VipNetdiskItem[] + desc: string +} { + const hit = resolveLessonMaterials(getCachedRemoteConfig(), lessonKey) + if (!hit?.url) return { items: [], desc: '' } + return { + items: [ + { + id: `lesson-${lessonKey}`, + title: hit.title || '课程资料下载', + desc: hit.desc || '', + url: hit.url, + }, + ], + desc: hit.desc || '', + } +} + export default function VipLessonPage() { const theme = useNomadroTheme() const router = useRouter() const m = Number(router.params?.m || 0) const l = Number(router.params?.l || 0) const prefs = useMemo(() => loadReaderPrefs() || DEFAULT_PREFS, []) - const [lesson, setLesson] = useState(null) - const [videoUrl, setVideoUrl] = useState('') + const localLesson = useMemo(() => getVipLesson(m, l), [m, l]) + const [lesson, setLesson] = useState(() => localLesson) + const [videoUrl, setVideoUrl] = useState(() => + encodeVideoSrc(localLesson?.videoUrl || ''), + ) const [markdown, setMarkdown] = useState('') const [modules, setModules] = useState(VIP_COURSE_MODULES) - const [isVip, setIsVip] = useState(false) - const [ready, setReady] = useState(false) + const [isVip, setIsVip] = useState(() => + hasVipContentAccessSync(isVipPaidLocal()), + ) + const lessonKey = localLesson?.key || `${m}-${l}` + const [materials, setMaterials] = useState(() => materialsForLesson(lessonKey)) + const [netdiskItem, setNetdiskItem] = useState(null) const nav = useMemo(() => findPrevNext(modules, m, l), [modules, m, l]) const { prev, next, total: TOTAL } = nav const [progress, setProgress] = useState(() => getProgress(TOTAL)) useEffect(() => { - setReady(false) + setLesson(localLesson) + setVideoUrl(encodeVideoSrc(localLesson?.videoUrl || '')) + setMarkdown('') + setMaterials(materialsForLesson(localLesson?.key || `${m}-${l}`)) + + let cancelled = false void (async () => { - const loaded = await loadVipLesson(m, l) - setLesson(loaded.lesson) - setModules(loaded.modules) - setVideoUrl(loaded.doc.videoUrl || loaded.lesson?.videoUrl || '') - setMarkdown(loaded.doc.markdown || '') - const vip = await resolveVipContentAccess(true) + const vip = await resolveVipContentAccess(false) + if (cancelled) return setIsVip(vip) - setReady(true) - const tot = loaded.modules.reduce((s, mod) => s + mod.lessons.length, 0) - setProgress(getProgress(tot)) if (!vip) { Taro.showModal({ title: '会员专享', @@ -75,14 +118,59 @@ export default function VipLessonPage() { }) }, }) - } else if (loaded.lesson) { + return + } + + const loaded = await loadVipLesson(m, l) + if (cancelled) return + setLesson(loaded.lesson || localLesson) + setModules(loaded.modules) + const nextUrl = encodeVideoSrc( + loaded.doc.videoUrl || loaded.lesson?.videoUrl || localLesson?.videoUrl || '', + ) + if (nextUrl) setVideoUrl(nextUrl) + setMarkdown(loaded.doc.markdown || '') + const tot = loaded.modules.reduce((s, mod) => s + mod.lessons.length, 0) + setProgress(getProgress(tot)) + if (loaded.lesson) { setLastWatched(m, l, loaded.lesson.name) Taro.setNavigationBarTitle({ title: loaded.lesson.name.replace(/^\d+\s*/, '').slice(0, 12), }) } + try { + const res = await loadRemoteConfig(false) + if (cancelled) return + const key = loaded.lesson?.key || localLesson?.key || `${m}-${l}` + // 用最新配置再解析一次(仍只认该课时单独配置) + const hit = resolveLessonMaterials(res.config, key) + if (hit?.url) { + setMaterials({ + items: [ + { + id: `lesson-${key}`, + title: hit.title || '课程资料下载', + desc: hit.desc || '', + url: hit.url, + }, + ], + desc: hit.desc || '', + }) + } else { + setMaterials({ items: [], desc: '' }) + } + } catch { + /* 离线用缓存 */ + } })() - }, [m, l]) + return () => { + cancelled = true + } + }, [m, l, localLesson]) + + useEffect(() => { + return subscribeVipAccess((vip) => setIsVip(hasVipContentAccessSync(vip))) + }, []) function onVideoEnded() { markCompleted(m, l) @@ -101,9 +189,11 @@ export default function VipLessonPage() { ) } + const showMaterials = isVip && materials.items.length > 0 + return ( - {ready && isVip ? ( + {isVip && videoUrl ? ( ) } diff --git a/apps/miniprogram/h5/src/pages/vip/index.tsx b/apps/miniprogram/h5/src/pages/vip/index.tsx index acb2d59..88dee7c 100644 --- a/apps/miniprogram/h5/src/pages/vip/index.tsx +++ b/apps/miniprogram/h5/src/pages/vip/index.tsx @@ -1,10 +1,9 @@ /** * Taro VIP landing — mirrors modules/vip LandingPage structure. - * 微信:读 platforms.weapp.vipContent;缺省=包内 DEFAULT(现网 UI);抖音不读 weapp。 */ import { useEffect, useMemo, useState } from 'react' import { Text, Button, View } from '@tarojs/components' -import Taro, { useDidShow, useRouter } from '@tarojs/taro' +import Taro, { useDidShow } from '@tarojs/taro' import { MiniModuleGate } from '@/components/MiniModuleGate' import { H5Box, H5Txt } from '@/components/H5Box' import { payVirtualProduct } from '@/utils/virtualPay' @@ -13,42 +12,121 @@ import { loadRemoteConfig, subscribeRemoteConfig, } from '@/services/remoteConfig' -import { - resolveBookAudit, - type NomadroRemoteConfig, -} from '@/data/remoteConfig.defaults' -import { - mergeWeappVipContent, - resolveWeappVipContent, - visibleItems, - type WeappVipContent, -} from '@/data/vipContent' -import { APP_TARGET } from '@/utils/config' +import type { NomadroRemoteConfig } from '@/data/remoteConfig.defaults' import { useNomadroTheme } from '@/utils/h5Theme' import { goHome, goPage } from '@/utils/nav' import { usePageShare, markPageShare } from '@/utils/pageShare' import { getSafeAreaMetrics } from '@/utils/safeArea' import { - isVipPaidLocal, markVipPaidLocal, resolveVipAccess, subscribeVipAccess, } from '@/utils/vipAccess' import { ensureLogin } from '@/utils/request' +import { fetchVipBridgeStatus } from '@/utils/vipWebAccount' +import { + resolveWeappVipContent, + visibleItems, + type VipNetdiskItem, +} from '@/data/vipContent' +import { VipLoginModal } from '@/components/VipLoginModal' +import { NetdiskShareModal } from '@/components/NetdiskShareModal' import './index.scss' const isH5 = process.env.TARO_ENV === 'h5' -/** 隐藏 CTA 次按钮 / 支付提示文案(逻辑保留,改 true 可恢复) */ -const SHOW_CTA_SECONDARY = false -const SHOW_CTA_PAY_HINT = false +/** Offline seed;电子书数量以 vipContent 为准(含 Youtube运营笔记) */ +const ASSET_STATS = { + topics: 4, + ebooks: 3, + videos: '40+', + updateFrequency: '每周', +} as const const STAT_ITEMS = [ - { key: 'topics' as const, label: '模块' }, - { key: 'ebooks' as const, label: '电子书' }, - { key: 'videos' as const, label: '视频' }, - { key: 'updateFrequency' as const, label: '更新' }, -] + { key: 'topics', label: '模块' }, + { key: 'ebooks', label: '电子书' }, + { key: 'videos', label: '视频' }, + { key: 'updateFrequency', label: '更新' }, +] as const + +/** Offline seeds from modules/vip/app/data/vip.mock.ts */ +const TOPICS_DISPLAY = [ + { id: 'ebook', icon: '📖', title: '电子书', desc: '知识沉淀·随时阅读', href: '#ebooks' }, + { id: 'cloudphone', icon: '🎬', title: '视频教程', desc: '实战演练·即学即用', href: '#video-courses' }, + { + id: 'community', + icon: '👥', + title: '知识社群', + desc: '抱团出海', + href: '/pages/vip-memo/index', + locked: true, + }, + { + id: 'tools', + icon: '🛒', + title: '设备自助下单', + desc: '开箱即用', + href: '/pages/vip-store/index', + locked: true, + }, +] as const + +const VIDEO_COURSES_DISPLAY = [ + { + id: 'cloudphone', + icon: '☁️', + title: '云手机', + desc: '低成本自建云手机,TikTok/YouTube 无人直播实战指南', + href: '/vip/cloudphone', + }, + { + id: 'livestream', + icon: '📺', + title: '无人直播', + desc: 'TikTok/YouTube 无人直播,24 小时自动化', + href: '/vip/topic/livestream', + }, + { + id: 'indie', + icon: '🛠️', + title: '独立开发', + desc: '从想法到产品,独立开发者全流程指南', + href: '/vip/topic/indie', + }, + { + id: 'aiagent', + icon: '🤖', + title: 'AI Agent', + desc: 'AIGC 与智能体,Vibe Coding 跨界创造', + href: '/vip/topic/aiagent', + }, +] as const + +const COMPARE_ITEMS = [ + { feature: '电子书', single: '按需开通', member: '全解锁' }, + { feature: '视频教程', single: '按需开通', member: '全解锁' }, + { feature: '知识社群', single: '—', member: '✓' }, + { feature: '即时问答', single: '—', member: '✓' }, + { feature: '持续更新', single: '—', member: '✓' }, +] as const + +const FAQ_ITEMS = [ + { + q: '会员包含哪些内容?', + a: '电子书、视频教程、知识社群、即时问答、设备自助下单等全部解锁,并享受持续更新。', + }, + { + q: '如何加入?', + a: '点击「立即加入」完成支付即可,支付成功后自动开通,无需人工审核。', + }, + { + q: '为什么越早加入越划算?', + a: '会员采用阶梯定价:越早锁定席位,单价越低;在恢复原价前完成支付,可长期享受全部内容与后续更新,整体投入更省、权益不打折。', + }, +] as const + +const CTA_CHIPS = ['阶梯定价', '数字交付', '持续更新', '不支持退款'] as const const LOGO_SVG = `