Merge branch 'master' of https://git.genarrative.world/GenarrativeAI/Genarrative
This commit is contained in:
@@ -32,6 +32,7 @@ temp*build*/
|
||||
/logs
|
||||
.worktrees/
|
||||
.env.secrets.local
|
||||
spacetime.local.json
|
||||
|
||||
# Local load-test data extracted from private migration files
|
||||
scripts/loadtest/data/*.local.json
|
||||
|
||||
@@ -69,6 +69,8 @@ npm run dev:web
|
||||
npm run api-server
|
||||
```
|
||||
|
||||
该命令会保留终端实时输出,并把同一份输出持久化到 `logs/api-server/api-server-<timestamp>.log`。完整联调入口 `npm run dev` / `npm run dev:rust` 启动的 Rust `api-server` 也会写入 `logs/api-server/api-server-dev-rust-<timestamp>.log`。如需改写路径,可设置 `GENARRATIVE_API_SERVER_LOG_FILE`;如只改目录,可设置 `GENARRATIVE_API_SERVER_LOG_DIR`。
|
||||
|
||||
查看本地 Rust/SpacetimeDB 日志:
|
||||
|
||||
```bash
|
||||
@@ -159,6 +161,8 @@ npm run check:server-rs-ddd
|
||||
- 检查 `/healthz`。
|
||||
- 执行对应自动测试。
|
||||
- 涉及 SpacetimeDB 表、reducer、procedure、row shape 或绑定变化时,同步更新 `migration.rs`、表目录和生成绑定。
|
||||
- SpacetimeDB 已有表新增字段必须放在 Rust 表结构体最后,并设置明确默认值;需要修改字段名时,先询问用户并确认迁移计划,再同步更新 `server-rs/crates/spacetime-module/src/migration.rs`、表目录和生成绑定。
|
||||
- 修改 SpacetimeDB schema 后运行 `npm run check:spacetime-schema`,用自动检查拦截缺 default、插入中间、字段删除/改名/重排/改类型,以及漏改迁移、表目录或绑定。
|
||||
|
||||
关键文档:
|
||||
|
||||
|
||||
@@ -282,8 +282,8 @@
|
||||
|
||||
- 现象:发布时 schema 冲突、自动迁移拒绝、旧客户端调用 reducer 失败、private 表数据迁移遗漏。
|
||||
- 原因:SpacetimeDB 对字段删除、类型变化、索引/主键/RLS/reducer 变化有不同自动迁移边界。
|
||||
- 处理:变更前阅读 `SPACETIMEDB_SCHEMA_CHANGE_CONSTRAINTS.md`;涉及表变化时同步 `migration.rs`、`SPACETIMEDB_TABLE_CATALOG.md` 和 bindings;必要时走 JSON 导入导出与分片导入迁移流程。
|
||||
- 验证:发布前完成 schema 检查、bindings 生成、表目录更新和相关 smoke。
|
||||
- 处理:变更前阅读 `SPACETIMEDB_SCHEMA_CHANGE_CONSTRAINTS.md`;已有表新增字段必须放在 Rust 表结构体最后并设置明确默认值;需要修改字段名时,先询问用户并确认迁移计划;涉及表变化时同步 `migration.rs`、`SPACETIMEDB_TABLE_CATALOG.md` 和 bindings;必要时走 JSON 导入导出与分片导入迁移流程。
|
||||
- 验证:发布前运行 `npm run check:spacetime-schema`,完成 schema 检查、bindings 生成、表目录更新和相关 smoke。
|
||||
- 关联:`docs/technical/SPACETIMEDB_SCHEMA_CHANGE_CONSTRAINTS.md`、`docs/technical/SPACETIMEDB_TABLE_CATALOG.md`。
|
||||
|
||||
## SpacetimeDB publish 报 wasm-bindgen 时先查 shared-contracts feature
|
||||
@@ -724,9 +724,18 @@
|
||||
- 现象:微信小程序支付下单能返回 `prepay_id`,但真实支付通知验签失败,或者本地实现误把商户 API 私钥当作回调验签 key。
|
||||
- 原因:商户私钥只用于商户请求微信支付和生成小程序 `paySign`;微信支付通知的 `Wechatpay-Signature` 需要使用微信支付平台公钥或平台证书公钥验签,并按通知头里的平台序列号匹配。
|
||||
- 处理:api-server 真实微信支付配置同时需要商户私钥与微信平台公钥:`WECHAT_PAY_PRIVATE_KEY_*` 用于签名,`WECHAT_PAY_PLATFORM_PUBLIC_KEY_*` 与 `WECHAT_PAY_PLATFORM_SERIAL_NO` 用于通知验签,`WECHAT_PAY_API_V3_KEY` 只用于解密通知 resource。支付成功后只通过通知里的 `out_trade_no` 确认本地 pending 订单,并保存 `transaction_id` 到 `profile_recharge_order.provider_transaction_id`。
|
||||
- APIv3 通知成功应答使用 HTTP `204 No Content`,不要沿用 V2 XML 成功报文;失败仍返回 4XX/5XX 让微信重试。
|
||||
- 验证:mock 通知测试只能覆盖本地回调推进;真实环境还需用微信支付平台公钥、真实通知头和 API v3 密钥验证签名与解密链路。
|
||||
- 关联:`server-rs/crates/api-server/src/wechat_pay.rs`、`docs/technical/MY_TAB_ACCOUNT_RECHARGE_IMPLEMENTATION_2026-04-25.md`。
|
||||
|
||||
## 微信支付 JSAPI 下单必须显式带 User-Agent
|
||||
|
||||
- 现象:调用 `/v3/pay/transactions/jsapi` 失败,微信返回“Http头缺少Accept或User-Agent”。
|
||||
- 原因:`reqwest` 请求即使已设置 `Accept: application/json`,也不会默认附带业务侧 `User-Agent`;微信支付网关会校验这两个头。
|
||||
- 处理:`api-server` 的 JSAPI 下单请求统一通过 `with_wechat_pay_jsapi_headers(...)` 设置 `Accept: application/json`、`Content-Type: application/json` 和 `User-Agent: Genarrative-WechatPay/1.0`。
|
||||
- 验证:执行 `cargo test -p api-server jsapi_order_request_sets_wechat_required_http_headers --manifest-path server-rs/Cargo.toml`。
|
||||
- 关联:`server-rs/crates/api-server/src/wechat_pay.rs`、`docs/technical/MY_TAB_ACCOUNT_RECHARGE_IMPLEMENTATION_2026-04-25.md`。
|
||||
|
||||
## 后台表查询展示 SpacetimeDB 枚举时不要套用 Option 解码
|
||||
|
||||
- 现象:后台“表查询”查看 `profile_recharge_order` 时,`kind` 和 `status` 显示为空数组 `[]`,例如充值订单原始行里 `points_60` 的类型和状态都不可读。
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# api-server 能力模块化与生成资产 Adapter 完整收口计划
|
||||
# api-server 能力模块化与生成资产 Adapter 完整收口计划
|
||||
|
||||
状态:待执行
|
||||
|
||||
|
||||
@@ -50,6 +50,8 @@ Single-context layout: read root `CONTEXT.md` when present and architecture deci
|
||||
- 后端最新技术约束以 [`docs/technical/SERVER_RS_DDD_FULL_REFACTOR_2026-04-28.md`](docs/technical/SERVER_RS_DDD_FULL_REFACTOR_2026-04-28.md) 为总纲;执行和收口状态以 [`docs/technical/SERVER_RS_DDD_PARALLEL_TASKLIST_2026-04-29.md`](docs/technical/SERVER_RS_DDD_PARALLEL_TASKLIST_2026-04-29.md) 为准。
|
||||
- 契约、路由、DTO 去留和 breaking change 以 [`docs/technical/SERVER_RS_DDD_G1_CONTRACT_AND_ROUTE_MATRIX_2026-04-29.md`](docs/technical/SERVER_RS_DDD_G1_CONTRACT_AND_ROUTE_MATRIX_2026-04-29.md) 为准;不得在前端、`api-server` 或临时兼容层中重新发明旧接口。
|
||||
- SpacetimeDB 表结构、自动迁移限制和冲突处理以 [`docs/technical/SPACETIMEDB_SCHEMA_CHANGE_CONSTRAINTS.md`](docs/technical/SPACETIMEDB_SCHEMA_CHANGE_CONSTRAINTS.md) 为准;涉及 table、reducer、procedure、row shape 或绑定变化时,必须同步 `migration.rs`、表目录和生成绑定。
|
||||
- SpacetimeDB 已有表新增字段时,字段必须放在 Rust 表结构体最后,并设置明确默认值(例如 `#[default(...)]`);需要修改字段名时,必须先询问用户并确认迁移计划,再改代码,同时更新 `server-rs/crates/spacetime-module/src/migration.rs`、表目录和生成绑定。
|
||||
- 修改 SpacetimeDB schema 后必须运行 `npm run check:spacetime-schema`;该检查会拦截新增字段缺 default、字段不在末尾、字段删除/改名/重排/改类型,以及漏改 `migration.rs`、表目录或生成绑定。
|
||||
- 后端路线固定为 `server-rs + Axum + SpacetimeDB`。旧 `server-node`、Express、PostgreSQL 不再作为兼容目标;历史实现只能作为迁移参考,若旧文档与 DDD 约束冲突,先修正文档和方案再编码。
|
||||
- DDD 分层边界按总纲执行:领域规则沉到 `module-*`,SpacetimeDB 表和事务编排留在 `spacetime-module`,后端访问 SpacetimeDB 统一经 `spacetime-client` facade,HTTP/SSE/BFF 留在 `api-server`,外部副作用留在 `platform-*`,前后端 DTO 留在 `shared-contracts`。
|
||||
- 前端只做表现、交互和临时 UI 状态,不承接正式业务真相,不绕过后端投影或后端 API 直接实现业务规则。
|
||||
|
||||
@@ -64,7 +64,8 @@
|
||||
|
||||
1. 校验 `productId`
|
||||
2. `paymentChannel = "mock"` 时后端创建已支付订单
|
||||
3. `paymentChannel = "wechat_mp"` 时后端创建待支付订单,并调用微信支付 JSAPI 下单生成小程序支付参数
|
||||
3. `paymentChannel = "wechat_mp"` 时后端创建待支付订单,并调用微信支付 JSAPI 下单生成小程序支付参数;本地 `orderId` 会作为微信 `out_trade_no` 传递,格式固定为 `rcg` 前缀 + 小写字母数字,长度在 6-32 字符内,满足微信支付 JSAPI 下单文档对商户订单号的限制。商品描述限制为 127 字符内,回调地址限制为 HTTPS、255 字符内且不携带 query/fragment。
|
||||
- JSAPI 下单请求必须显式携带 `Accept: application/json`、`Content-Type: application/json` 和 `User-Agent: Genarrative-WechatPay/1.0`;微信侧会把缺少 `User-Agent` 的请求返回为“Http头缺少Accept或User-Agent”。
|
||||
4. mock 泥点套餐立即写入钱包余额与流水,mock 会员套餐立即写入会员状态
|
||||
5. wechat_mp 订单不提前发泥点或会员,只返回待支付订单、账户中心快照与 `wechatMiniProgramPayParams`
|
||||
|
||||
@@ -84,16 +85,42 @@
|
||||
}
|
||||
```
|
||||
|
||||
### 3.3 `POST /api/profile/recharge/wechat/notify`
|
||||
### 3.3 `POST /api/profile/recharge/orders/{order_id}/wechat/confirm`
|
||||
|
||||
需要 Bearer JWT。该接口用于小程序支付页返回 web-view 后的主动查单确认,不替代微信支付通知:
|
||||
|
||||
1. 后端读取本地 `profile_recharge_order` 并校验订单归属、支付渠道和当前状态。
|
||||
2. 若订单已是 `paid`,直接返回订单与账户中心快照。
|
||||
3. 若订单仍是 `pending`,后端调用微信支付按商户订单号查单接口。
|
||||
4. 只有微信查单返回 `trade_state = "SUCCESS"` 时,才调用统一入账 procedure 把订单改为 `paid` 并写入钱包流水或会员状态。
|
||||
5. 如果微信查单仍不是 `SUCCESS`,接口返回当前 pending 订单与账户中心快照;前端只在全局支付结果模态显示“支付已提交”,不提前发放泥点或会员。
|
||||
|
||||
响应结构:
|
||||
|
||||
```json
|
||||
{
|
||||
"order": {
|
||||
"orderId": "rcg...",
|
||||
"status": "paid"
|
||||
},
|
||||
"center": {
|
||||
"walletBalance": 120
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 3.4 `POST /api/profile/recharge/wechat/notify`
|
||||
|
||||
微信支付通知地址,无需 Bearer JWT。行为:
|
||||
|
||||
1. 真实渠道使用微信支付平台公钥和 `Wechatpay-*` 请求头验签。
|
||||
1. 真实渠道使用微信支付平台公钥和 `Wechatpay-*` 请求头验签;验签必须使用原始 HTTP body bytes 构造 `timestamp\nnonce\nbody\n`,不能先把 body 转成字符串再重建。
|
||||
2. 使用 `WECHAT_PAY_API_V3_KEY` 解密通知 `resource`。
|
||||
3. 仅当 `trade_state = "SUCCESS"` 时确认订单支付。
|
||||
4. 使用微信通知里的 `out_trade_no` 查本地 `profile_recharge_order.order_id`,把订单从 `pending` 改为 `paid`。
|
||||
5. 将微信平台订单号写入 `provider_transaction_id`,用于对账、查单、退款和客服排障。
|
||||
6. 在同一 SpacetimeDB procedure 内写入钱包流水或会员到期时间,确保重复通知幂等。
|
||||
7. 验签、解密和业务确认通过后返回 HTTP `204 No Content`;不要返回 V2 XML。
|
||||
8. 微信支付公钥模式下,真实请求会携带 `Wechatpay-Serial: PUB_KEY_ID_...`,通知验签必须要求回调头 `Wechatpay-Serial` 与 `WECHAT_PAY_PLATFORM_SERIAL_NO` 对应;若不匹配应返回 `401` 并在日志里记录 reason。
|
||||
|
||||
关键环境变量:
|
||||
|
||||
@@ -115,8 +142,14 @@
|
||||
2. 弹窗顶部标题为 `账户充值`,右上角关闭。
|
||||
3. 默认打开 `泥点充值`,可切换到 `会员卡充值`。
|
||||
4. 点击套餐后调用下单接口,按钮进入处理中状态;小程序环境走 native 支付页拉起 `wx.requestPayment`,支付页返回后刷新 `profileDashboard`。
|
||||
5. 弹窗内不写大段说明文案,只保留必要金额、泥点、会员权益和状态反馈。
|
||||
6. 会员卡充值区以套餐卡片优先展示周期、价格和处理状态;移动端单列,桌面端三列,权益表允许横向滚动,避免小屏挤压。
|
||||
- 小程序 web-view 内的 H5 只负责加载微信 JS-SDK 并通过 `wx.miniProgram.navigateTo` 跳转到 `/pages/wechat-pay/index`;实际支付必须在小程序 native 页调用 `wx.requestPayment`,不要切换为 H5 支付产品。
|
||||
- native 支付页通过 `wx_pay_result=<requestId>:success|cancel|fail` 回填 web-view;H5 在 `hashchange`、`focus`、`pageshow` 和 `visibilitychange` 中都会尝试消费该结果,避免小程序返回 web-view 时没有触发单一事件导致状态不刷新。
|
||||
- `success` 只表示微信客户端支付流程返回成功,前端随后调用 `POST /api/profile/recharge/orders/{order_id}/wechat/confirm` 由服务端查单确认;只有通知或服务端查单确认为 `SUCCESS` 才入账。
|
||||
- 小程序返回后,前端会对确认接口做短轮询,覆盖微信通知/查单结果与 web-view 恢复之间的秒级时间差;只有确认响应里的订单状态变成 `paid` 后,才触发父级 `profileDashboard` 刷新,确保“我的”页泥点卡片读取到最新余额。
|
||||
- `cancel` 和 `fail` 只复位按钮、刷新账户中心并通过全局支付结果模态展示,不调用入账逻辑。
|
||||
5. 支付结果使用页面级全局模态展示,不写回商品卡片或账户充值弹窗内部;充值弹窗只负责套餐选择、加载失败和下单失败。
|
||||
6. 弹窗内不写大段说明文案,只保留必要金额、泥点、会员权益和操作状态。
|
||||
7. 会员卡充值区以套餐卡片优先展示周期、价格和处理状态;移动端单列,桌面端三列,权益表允许横向滚动,避免小屏挤压。
|
||||
|
||||
## 5. 验收
|
||||
|
||||
|
||||
@@ -49,7 +49,7 @@ npm run dev:rust
|
||||
5. 如果确认需要新启动 SpacetimeDB,脚本会先检测 `127.0.0.1:3101` 是否可监听;若已占用,输出占用进程并选择从 `3101` 起向后的最近可用端口,再执行 `spacetime start --data-dir server-rs/.spacetimedb/local/data --listen-addr <实际地址>`。启动成功后把实际 URL 写入 `server-rs/.spacetimedb/local/data/dev-rust-spacetime-url`,后续 publish 与 `api-server` 都使用同一个实际 URL。
|
||||
6. 等待 SpacetimeDB 就绪:优先接受 `spacetime server ping http://127.0.0.1:<spacetime-port>` 输出中的 `Server is online:`;如果 Windows 下 SpacetimeDB CLI `2.1.0` 对已经监听的 standalone 仍打印 `502 Bad Gateway`,脚本会兜底请求 `http://127.0.0.1:<spacetime-port>/v1/ping`,只有该健康端点返回 `2xx` 时才放行。不能只依赖 CLI 退出码,因为 CLI 在 `502 Bad Gateway` 时也可能返回退出码 `0`。
|
||||
7. 执行 `spacetime publish <本地数据库名> --server <实际 SpacetimeDB URL> --module-path server-rs/crates/spacetime-module --build-options="--debug" -c=on-conflict --yes`,确保 publish 仍由 SpacetimeDB CLI 负责构建和发布模块,同时使用 debug 构建参数降低本地开发等待时间;当前开发阶段允许新版模块表结构变化且发生 schema 冲突时清除旧模块数据。
|
||||
8. 启动 `api-server` 前先检测默认 API 端口 `8082` 是否可监听;若已占用,输出占用进程并选择从 `8082` 起向后的最近可用端口。随后注入 `GENARRATIVE_API_*` 与 `GENARRATIVE_SPACETIME_*`,启动默认 debug profile 的 `cargo run -p api-server`;直接运行 `api-server` 时,如未显式设置 `GENARRATIVE_SPACETIME_DATABASE`,服务端也会向上查找 `spacetime.local.json` 作为本地默认库名。
|
||||
8. 启动 `api-server` 前先检测默认 API 端口 `8082` 是否可监听;若已占用,输出占用进程并选择从 `8082` 起向后的最近可用端口。随后注入 `GENARRATIVE_API_*` 与 `GENARRATIVE_SPACETIME_*`,启动默认 debug profile 的 `cargo run -p api-server`;直接运行 `api-server` 时,如未显式设置 `GENARRATIVE_SPACETIME_DATABASE`,服务端也会向上查找 `spacetime.local.json` 作为本地默认库名。本地启动器会保留终端实时输出,并把同一份 `cargo` / `api-server` 输出持久化到 `logs/api-server/`。
|
||||
9. 等待 `http://127.0.0.1:<api-port>/healthz` 返回 HTTP 响应后再启动 Vite,避免前端初始化请求早于 Rust `api-server` 监听完成并在终端刷出 `ECONNREFUSED 127.0.0.1:<api-port>`。
|
||||
10. 注入 `RUST_SERVER_TARGET`、`GENARRATIVE_RUNTIME_SERVER_TARGET` 后启动 Vite。
|
||||
11. 任一子进程退出时,脚本回收其余子进程。
|
||||
@@ -120,6 +120,12 @@ npm run dev:rust:logs -- --follow
|
||||
3. 默认输出到 `logs/spacetime/<database>-<timestamp>.log`,并通过 `tee` 同步显示在终端。
|
||||
4. `--follow` 仅用于本地追踪,会持续追加到同一个输出文件;停止时用 `Ctrl+C`。
|
||||
|
||||
api-server 本地持久化日志:
|
||||
|
||||
1. `npm run api-server` 默认写入 `logs/api-server/api-server-<timestamp>.log`,同时继续把同一份输出显示在当前终端。
|
||||
2. `npm run dev` / `npm run dev:rust` 中由脚本启动的 Rust `api-server` 默认写入 `logs/api-server/api-server-dev-rust-<timestamp>.log`;等待 `/healthz` 失败时,脚本会自动输出该日志最后 80 行。
|
||||
3. 如需固定日志文件,可设置 `GENARRATIVE_API_SERVER_LOG_FILE=logs/api-server/local.log`;如只需更换目录,可设置 `GENARRATIVE_API_SERVER_LOG_DIR=logs/api-server`。相对路径都按仓库根目录解析。
|
||||
|
||||
联调排错补充:
|
||||
|
||||
1. 如果首页公开广场出现 `上游服务请求失败`,优先检查 `api-server` 错误详情里的 `ws://.../v1/database/<database>/subscribe` 是否指向了未发布的库。
|
||||
|
||||
@@ -58,6 +58,14 @@ host 会比较新模块声明的 schema 和旧数据库 schema,然后尝试自
|
||||
4. 等数据迁移完成、旧客户端完成升级、旧表数据清空后,再移除旧表。
|
||||
5. 开发环境可以使用 `--delete-data` 重建数据库,生产环境不要用它作为数据迁移方案。
|
||||
|
||||
## 字段级硬性约束
|
||||
|
||||
- 对已有 SpacetimeDB 表新增字段时,必须把新字段追加在 Rust 表结构体的最后,不能插入已有字段中间。
|
||||
- 新增字段必须设置明确默认值,例如 Rust `#[default(...)]`;复杂集合默认值如果无法作为编译期常量表达,应优先使用 `Option<T>` 加 `#[default(None::<T>)]`,并在业务层归一化。
|
||||
- 修改已有字段名属于高风险 schema 变更。编码前必须先询问用户,确认旧字段名、新字段名、数据保留方式、客户端兼容窗口和发布顺序,并让用户准备或确认迁移计划。
|
||||
- 字段改名或任何 row shape 迁移都必须同步更新 `server-rs/crates/spacetime-module/src/migration.rs`、`SPACETIMEDB_TABLE_CATALOG.md` 和生成绑定;不要只改表结构体。
|
||||
- 修改 SpacetimeDB schema 后必须运行 `npm run check:spacetime-schema`。该检查会对比当前工作区与基准分支的 Rust table 字段,自动拦截新增字段缺 default、字段插入中间、字段删除/改名/重排/改类型,以及漏改 `migration.rs`、表目录或生成绑定。
|
||||
|
||||
## 通常安全的变更
|
||||
|
||||
这些变更一般可以自动迁移,并且通常不会破坏现有客户端:
|
||||
@@ -223,6 +231,8 @@ fn migrate_character_batch(ctx: &ReducerContext, limit: u32) {
|
||||
|
||||
- 是否删除、改名、重排或修改了已有列。
|
||||
- 新增列是否位于表定义末尾,并且是否有 default value。
|
||||
- 如需改字段名,是否已先询问用户并确认迁移计划,且已同步更新 `migration.rs`。
|
||||
- 是否已运行 `npm run check:spacetime-schema` 并通过。
|
||||
- 是否给已有表新增了 unique 或 primary key 约束。
|
||||
- 是否删除了非空表。
|
||||
- 是否修改了 event table、schedule table、RLS 或 view。
|
||||
|
||||
@@ -9,6 +9,7 @@ const {
|
||||
const MINI_PROGRAM_CLIENT_TYPE = 'mini_program';
|
||||
const MINI_PROGRAM_CLIENT_RUNTIME = 'wechat_mini_program';
|
||||
const CLIENT_INSTANCE_STORAGE_KEY = 'genarrative:mini-program-client-instance-id';
|
||||
const PAY_RESULT_STORAGE_KEY = 'genarrative:wechat-pay-result';
|
||||
|
||||
function isConfiguredEntryUrl(value) {
|
||||
const trimmed = String(value || '').trim();
|
||||
@@ -273,6 +274,20 @@ Page({
|
||||
}
|
||||
},
|
||||
|
||||
onShow() {
|
||||
const result = wx.getStorageSync(PAY_RESULT_STORAGE_KEY);
|
||||
if (!result || !this.data.webViewUrl) {
|
||||
return;
|
||||
}
|
||||
|
||||
wx.removeStorageSync(PAY_RESULT_STORAGE_KEY);
|
||||
this.setData({
|
||||
webViewUrl: appendHashParams(this.data.webViewUrl, {
|
||||
wx_pay_result: result,
|
||||
}),
|
||||
});
|
||||
},
|
||||
|
||||
async handleGetPhoneNumber(event) {
|
||||
if (!this.data.authResult || !this.data.authResult.token) {
|
||||
this.handleRetryLogin();
|
||||
|
||||
@@ -30,18 +30,25 @@ function requestPayment(payParams) {
|
||||
});
|
||||
}
|
||||
|
||||
const PAY_RESULT_STORAGE_KEY = 'genarrative:wechat-pay-result';
|
||||
|
||||
function appendPayResult(url, requestId, status) {
|
||||
const value = `${requestId}:${status}`;
|
||||
const hashIndex = String(url || '').indexOf('#');
|
||||
const baseUrl =
|
||||
hashIndex >= 0 ? String(url).slice(0, hashIndex) : String(url || '');
|
||||
const rawHash = hashIndex >= 0 ? String(url).slice(hashIndex + 1) : '';
|
||||
const params = new URLSearchParams(rawHash);
|
||||
params.set('wx_pay_result', value);
|
||||
return `${baseUrl}#${params.toString()}`;
|
||||
const nextHash = rawHash
|
||||
.split('&')
|
||||
.filter((part) => part && !part.startsWith('wx_pay_result='))
|
||||
.concat(`wx_pay_result=${encodeURIComponent(value)}`)
|
||||
.join('&');
|
||||
return `${baseUrl}#${nextHash}`;
|
||||
}
|
||||
|
||||
function notifyPreviousWebView(requestId, status) {
|
||||
const result = `${requestId}:${status}`;
|
||||
wx.setStorageSync(PAY_RESULT_STORAGE_KEY, result);
|
||||
const pages = getCurrentPages();
|
||||
const previousPage = pages.length >= 2 ? pages[pages.length - 2] : null;
|
||||
if (previousPage && typeof previousPage.setData === 'function') {
|
||||
|
||||
+3
-2
@@ -23,17 +23,18 @@
|
||||
"preview": "node scripts/vite-cli.mjs preview",
|
||||
"clean": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\"",
|
||||
"check:encoding": "node scripts/check-encoding.mjs",
|
||||
"check:spacetime-schema": "node scripts/check-spacetime-schema-guard.mjs",
|
||||
"assets:child-motion-demo": "node scripts/generate-child-motion-demo-assets.mjs",
|
||||
"assets:match3d-style-references": "node scripts/generate-match3d-style-references.mjs",
|
||||
"check:visual-novel-vn11": "node scripts/check-visual-novel-vn11-negative-scan.mjs",
|
||||
"check:visual-novel-vn12": "node scripts/check-visual-novel-vn12-acceptance.mjs",
|
||||
"check:wechat-miniprogram-auth": "node scripts/check-wechat-miniprogram-auth-smoke.mjs",
|
||||
"check:server-rs-ddd": "node scripts/check-server-rs-ddd-boundaries.mjs",
|
||||
"check:server-rs-ddd": "npm run check:spacetime-schema && node scripts/check-server-rs-ddd-boundaries.mjs",
|
||||
"lint:eslint": "eslint . --ext .ts,.tsx,.js,.mjs,.cjs --max-warnings 0",
|
||||
"lint:guardrails": "npm run lint:eslint",
|
||||
"typecheck": "tsc -p tsconfig.typecheck-guardrails.json --noEmit",
|
||||
"typecheck:guardrails": "npm run typecheck",
|
||||
"lint": "npm run check:encoding && npm run lint:eslint && npm run typecheck",
|
||||
"lint": "npm run check:encoding && npm run check:spacetime-schema && npm run lint:eslint && npm run typecheck",
|
||||
"lint:fix": "eslint . --ext .ts,.tsx,.js,.mjs,.cjs --fix && prettier --write .",
|
||||
"format": "prettier --write .",
|
||||
"format:check": "prettier --check .",
|
||||
|
||||
@@ -158,6 +158,11 @@ export type CreateProfileRechargeOrderResponse = {
|
||||
wechatMiniProgramPayParams?: WechatMiniProgramPayParams | null;
|
||||
};
|
||||
|
||||
export type ConfirmWechatProfileRechargeOrderResponse = {
|
||||
order: ProfileRechargeOrder;
|
||||
center: ProfileRechargeCenterResponse;
|
||||
};
|
||||
|
||||
export type ProfileFeedbackStatus = 'open';
|
||||
|
||||
export type ProfileFeedbackEvidenceItemInput = {
|
||||
|
||||
+13
-3
@@ -12,7 +12,16 @@
|
||||
"outputPath": ""
|
||||
},
|
||||
"useCompilerPlugins": false,
|
||||
"minifyWXML": true
|
||||
"minifyWXML": true,
|
||||
"compileWorklet": false,
|
||||
"uploadWithSourceMap": true,
|
||||
"packNpmManually": false,
|
||||
"minifyWXSS": true,
|
||||
"localPlugins": false,
|
||||
"disableUseStrict": false,
|
||||
"condition": false,
|
||||
"swc": false,
|
||||
"disableSWC": true
|
||||
},
|
||||
"compileType": "miniprogram",
|
||||
"miniprogramRoot": "miniprogram/",
|
||||
@@ -22,5 +31,6 @@
|
||||
"include": []
|
||||
},
|
||||
"appid": "wx3da23ea14ca66b65",
|
||||
"editorSetting": {}
|
||||
}
|
||||
"editorSetting": {},
|
||||
"libVersion": "3.15.2"
|
||||
}
|
||||
@@ -2,13 +2,20 @@
|
||||
"libVersion": "3.15.2",
|
||||
"projectname": "Genarrative",
|
||||
"setting": {
|
||||
"urlCheck": true,
|
||||
"urlCheck": false,
|
||||
"coverView": true,
|
||||
"lazyloadPlaceholderEnable": false,
|
||||
"skylineRenderEnable": false,
|
||||
"preloadBackgroundData": false,
|
||||
"autoAudits": false,
|
||||
"showShadowRootInWxmlPanel": true,
|
||||
"compileHotReLoad": true
|
||||
"compileHotReLoad": true,
|
||||
"useApiHook": true,
|
||||
"useStaticServer": false,
|
||||
"useLanDebug": false,
|
||||
"showES6CompileOption": false,
|
||||
"checkInvalidKey": true,
|
||||
"ignoreDevUnusedFiles": true,
|
||||
"bigPackageSizeSupport": false
|
||||
}
|
||||
}
|
||||
+140
-18
@@ -1,6 +1,11 @@
|
||||
import { execFileSync, spawn } from 'node:child_process';
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import {
|
||||
createWriteStream,
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
readFileSync,
|
||||
} from 'node:fs';
|
||||
import { dirname, isAbsolute, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const repoRoot = process.cwd();
|
||||
@@ -67,7 +72,69 @@ export function mergeApiServerEnv(repoRootPath, baseEnv = process.env) {
|
||||
return mergedEnv;
|
||||
}
|
||||
|
||||
function stopExistingWindowsApiServer() {
|
||||
export function formatApiServerLogTimestamp(date = new Date()) {
|
||||
const pad = (value) => String(value).padStart(2, '0');
|
||||
|
||||
return [
|
||||
date.getFullYear(),
|
||||
pad(date.getMonth() + 1),
|
||||
pad(date.getDate()),
|
||||
'-',
|
||||
pad(date.getHours()),
|
||||
pad(date.getMinutes()),
|
||||
pad(date.getSeconds()),
|
||||
].join('');
|
||||
}
|
||||
|
||||
export function resolveApiServerLogFile(
|
||||
repoRootPath,
|
||||
env = process.env,
|
||||
now = new Date(),
|
||||
) {
|
||||
const explicitLogFile = String(
|
||||
env.GENARRATIVE_API_SERVER_LOG_FILE ?? '',
|
||||
).trim();
|
||||
|
||||
if (explicitLogFile) {
|
||||
return isAbsolute(explicitLogFile)
|
||||
? explicitLogFile
|
||||
: resolve(repoRootPath, explicitLogFile);
|
||||
}
|
||||
|
||||
const logDir =
|
||||
String(env.GENARRATIVE_API_SERVER_LOG_DIR ?? '').trim() ||
|
||||
'logs/api-server';
|
||||
const resolvedLogDir = isAbsolute(logDir)
|
||||
? logDir
|
||||
: resolve(repoRootPath, logDir);
|
||||
|
||||
return resolve(
|
||||
resolvedLogDir,
|
||||
`api-server-${formatApiServerLogTimestamp(now)}.log`,
|
||||
);
|
||||
}
|
||||
|
||||
function createApiServerLogStream(logFilePath) {
|
||||
mkdirSync(dirname(logFilePath), { recursive: true });
|
||||
const logStream = createWriteStream(logFilePath, {
|
||||
flags: 'a',
|
||||
encoding: 'utf8',
|
||||
});
|
||||
logStream.on('error', (error) => {
|
||||
console.error(`[api-server] 写入日志失败: ${error.message}`);
|
||||
});
|
||||
return logStream;
|
||||
}
|
||||
|
||||
function writeLauncherLog(logStream, message, stream = process.stdout) {
|
||||
const line = `${message}\n`;
|
||||
stream.write(line);
|
||||
if (!logStream.destroyed) {
|
||||
logStream.write(line);
|
||||
}
|
||||
}
|
||||
|
||||
function stopExistingWindowsApiServer(logStream) {
|
||||
if (process.platform !== 'win32') {
|
||||
return;
|
||||
}
|
||||
@@ -104,7 +171,7 @@ function stopExistingWindowsApiServer() {
|
||||
).trim();
|
||||
|
||||
if (output) {
|
||||
console.log(`[api-server] 已停止旧 api-server 进程: ${output}`);
|
||||
writeLauncherLog(logStream, `[api-server] 已停止旧 api-server 进程: ${output}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,19 +188,55 @@ function main() {
|
||||
mergedEnv.GENARRATIVE_SPACETIME_TOKEN =
|
||||
mergedEnv.GENARRATIVE_SPACETIME_TOKEN || '';
|
||||
|
||||
const logFilePath = resolveApiServerLogFile(repoRoot, mergedEnv);
|
||||
const logStream = createApiServerLogStream(logFilePath);
|
||||
mergedEnv.GENARRATIVE_API_SERVER_LOG_FILE = logFilePath;
|
||||
|
||||
let didExit = false;
|
||||
const exitAfterLogFlush = (code) => {
|
||||
const finish = () => {
|
||||
if (didExit) {
|
||||
return;
|
||||
}
|
||||
didExit = true;
|
||||
process.exit(code);
|
||||
};
|
||||
|
||||
if (logStream.destroyed) {
|
||||
finish();
|
||||
return;
|
||||
}
|
||||
|
||||
logStream.end(finish);
|
||||
setTimeout(finish, 1000).unref();
|
||||
};
|
||||
|
||||
writeLauncherLog(logStream, `[api-server] 日志: ${logFilePath}`);
|
||||
|
||||
if (!mergedEnv.GENARRATIVE_SPACETIME_DATABASE) {
|
||||
console.error('[api-server] 缺少 GENARRATIVE_SPACETIME_DATABASE。');
|
||||
process.exit(1);
|
||||
writeLauncherLog(
|
||||
logStream,
|
||||
'[api-server] 缺少 GENARRATIVE_SPACETIME_DATABASE。',
|
||||
process.stderr,
|
||||
);
|
||||
exitAfterLogFlush(1);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
stopExistingWindowsApiServer();
|
||||
stopExistingWindowsApiServer(logStream);
|
||||
} catch (error) {
|
||||
console.error(`[api-server] 清理旧 api-server 进程失败: ${error.message}`);
|
||||
process.exit(1);
|
||||
writeLauncherLog(
|
||||
logStream,
|
||||
`[api-server] 清理旧 api-server 进程失败: ${error.message}`,
|
||||
process.stderr,
|
||||
);
|
||||
exitAfterLogFlush(1);
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(
|
||||
writeLauncherLog(
|
||||
logStream,
|
||||
`[api-server] SpacetimeDB ${mergedEnv.GENARRATIVE_SPACETIME_DATABASE} @ ${mergedEnv.GENARRATIVE_SPACETIME_SERVER_URL}`,
|
||||
);
|
||||
|
||||
@@ -143,22 +246,41 @@ function main() {
|
||||
{
|
||||
cwd: repoRoot,
|
||||
env: mergedEnv,
|
||||
stdio: 'inherit',
|
||||
stdio: ['inherit', 'pipe', 'pipe'],
|
||||
},
|
||||
);
|
||||
|
||||
child.on('error', (error) => {
|
||||
console.error(`[api-server] 启动 cargo 失败: ${error.message}`);
|
||||
process.exit(1);
|
||||
child.stdout?.on('data', (chunk) => {
|
||||
process.stdout.write(chunk);
|
||||
logStream.write(chunk);
|
||||
});
|
||||
|
||||
child.on('exit', (code, signal) => {
|
||||
child.stderr?.on('data', (chunk) => {
|
||||
process.stderr.write(chunk);
|
||||
logStream.write(chunk);
|
||||
});
|
||||
|
||||
child.on('error', (error) => {
|
||||
writeLauncherLog(
|
||||
logStream,
|
||||
`[api-server] 启动 cargo 失败: ${error.message}`,
|
||||
process.stderr,
|
||||
);
|
||||
exitAfterLogFlush(1);
|
||||
});
|
||||
|
||||
child.on('close', (code, signal) => {
|
||||
if (signal) {
|
||||
console.error(`[api-server] api-server 被信号终止: ${signal}`);
|
||||
process.exit(1);
|
||||
writeLauncherLog(
|
||||
logStream,
|
||||
`[api-server] api-server 被信号终止: ${signal}`,
|
||||
process.stderr,
|
||||
);
|
||||
exitAfterLogFlush(1);
|
||||
return;
|
||||
}
|
||||
|
||||
process.exit(code ?? 0);
|
||||
exitAfterLogFlush(code ?? 0);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,11 @@ import { join } from 'node:path';
|
||||
|
||||
import { describe, expect, test } from 'vitest';
|
||||
|
||||
import { mergeApiServerEnv } from './api-server-dev.mjs';
|
||||
import {
|
||||
formatApiServerLogTimestamp,
|
||||
mergeApiServerEnv,
|
||||
resolveApiServerLogFile,
|
||||
} from './api-server-dev.mjs';
|
||||
|
||||
type EnvMap = Record<string, string>;
|
||||
|
||||
@@ -92,3 +96,39 @@ describe('api-server-dev env merge', () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('api-server-dev log file resolution', () => {
|
||||
const fixedDate = new Date(2026, 4, 15, 6, 7, 8);
|
||||
|
||||
test('默认写入 logs/api-server 的时间戳文件', () => {
|
||||
const tempDir = mkdtempSync(join(tmpdir(), 'genarrative-api-log-'));
|
||||
|
||||
try {
|
||||
expect(formatApiServerLogTimestamp(fixedDate)).toBe('20260515-060708');
|
||||
expect(resolveApiServerLogFile(tempDir, {}, fixedDate)).toBe(
|
||||
join(tempDir, 'logs/api-server/api-server-20260515-060708.log'),
|
||||
);
|
||||
} finally {
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('GENARRATIVE_API_SERVER_LOG_FILE 优先于日志目录默认值', () => {
|
||||
const tempDir = mkdtempSync(join(tmpdir(), 'genarrative-api-log-'));
|
||||
|
||||
try {
|
||||
expect(
|
||||
resolveApiServerLogFile(
|
||||
tempDir,
|
||||
{
|
||||
GENARRATIVE_API_SERVER_LOG_DIR: 'logs/ignored',
|
||||
GENARRATIVE_API_SERVER_LOG_FILE: 'logs/custom/api.log',
|
||||
},
|
||||
fixedDate,
|
||||
),
|
||||
).toBe(join(tempDir, 'logs/custom/api.log'));
|
||||
} finally {
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -658,11 +658,13 @@ wait_for_api_server() {
|
||||
local health_url="$1"
|
||||
local timeout_seconds="$2"
|
||||
local process_pid="${3:-}"
|
||||
local log_file="${4:-${API_SERVER_LOG_FILE:-}}"
|
||||
local deadline=$((SECONDS + timeout_seconds))
|
||||
|
||||
while ((SECONDS < deadline)); do
|
||||
if [[ -n "${process_pid}" ]] && ! kill -0 "${process_pid}" 2>/dev/null; then
|
||||
echo "[dev:rust] api-server 进程在就绪前退出。" >&2
|
||||
print_api_server_log_tail "${log_file}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -684,9 +686,58 @@ request.on("error", () => process.exit(1));
|
||||
done
|
||||
|
||||
echo "[dev:rust] 等待 api-server 就绪超时: ${health_url}" >&2
|
||||
print_api_server_log_tail "${log_file}"
|
||||
exit 1
|
||||
}
|
||||
|
||||
format_api_server_log_timestamp() {
|
||||
date +%Y%m%d-%H%M%S
|
||||
}
|
||||
|
||||
normalize_api_server_log_path() {
|
||||
local path_value="$1"
|
||||
|
||||
if [[ "${path_value}" == *\\* ]]; then
|
||||
path_value="${path_value//\\//}"
|
||||
fi
|
||||
|
||||
echo "${path_value}"
|
||||
}
|
||||
|
||||
resolve_api_server_log_file() {
|
||||
local explicit_log_file="${GENARRATIVE_API_SERVER_LOG_FILE:-}"
|
||||
local log_dir="${GENARRATIVE_API_SERVER_LOG_DIR:-${REPO_ROOT}/logs/api-server}"
|
||||
|
||||
if [[ -n "${explicit_log_file//[[:space:]]/}" ]]; then
|
||||
explicit_log_file="$(normalize_api_server_log_path "${explicit_log_file}")"
|
||||
if [[ "${explicit_log_file}" = /* || "${explicit_log_file}" =~ ^[A-Za-z]:[\\/] ]]; then
|
||||
echo "${explicit_log_file}"
|
||||
return
|
||||
fi
|
||||
|
||||
echo "${REPO_ROOT}/${explicit_log_file}"
|
||||
return
|
||||
fi
|
||||
|
||||
log_dir="$(normalize_api_server_log_path "${log_dir}")"
|
||||
if [[ ! "${log_dir}" = /* && ! "${log_dir}" =~ ^[A-Za-z]:[\\/] ]]; then
|
||||
log_dir="${REPO_ROOT}/${log_dir}"
|
||||
fi
|
||||
|
||||
echo "${log_dir}/api-server-dev-rust-$(format_api_server_log_timestamp).log"
|
||||
}
|
||||
|
||||
print_api_server_log_tail() {
|
||||
local log_file="${1:-}"
|
||||
|
||||
if [[ -z "${log_file}" || ! -f "${log_file}" ]]; then
|
||||
return
|
||||
fi
|
||||
|
||||
echo "[dev:rust] api-server 最近日志: ${log_file}" >&2
|
||||
tail -n 80 "${log_file}" >&2 || true
|
||||
}
|
||||
|
||||
|
||||
generate_migration_bootstrap_secret() {
|
||||
node -e 'const crypto = require("crypto"); process.stdout.write(crypto.randomBytes(32).toString("hex"));'
|
||||
@@ -995,22 +1046,26 @@ API_PORT="$(find_nearest_available_port "${API_HOST}" "${API_PORT}" "api-server"
|
||||
API_TARGET_HOST="$(resolve_client_host "${API_HOST}")"
|
||||
# `.env.local` 可以给单独 `dev:web` 配置代理目标,但完整栈的前端必须跟随本次 `--api-port`。
|
||||
RUST_SERVER_TARGET="http://${API_TARGET_HOST}:${API_PORT}"
|
||||
API_SERVER_LOG_FILE="$(resolve_api_server_log_file)"
|
||||
mkdir -p "$(dirname -- "${API_SERVER_LOG_FILE}")"
|
||||
echo "[dev:rust] api actual: ${RUST_SERVER_TARGET}"
|
||||
echo "[dev:rust] api-server log: ${API_SERVER_LOG_FILE}"
|
||||
(
|
||||
cd "${REPO_ROOT}"
|
||||
GENARRATIVE_API_HOST="${API_HOST}" \
|
||||
GENARRATIVE_API_PORT="${API_PORT}" \
|
||||
GENARRATIVE_API_LOG="${API_LOG}" \
|
||||
GENARRATIVE_API_SERVER_LOG_FILE="${API_SERVER_LOG_FILE}" \
|
||||
GENARRATIVE_SPACETIME_SERVER_URL="${SPACETIME_SERVER}" \
|
||||
GENARRATIVE_SPACETIME_DATABASE="${DATABASE}" \
|
||||
exec cargo run -p api-server --manifest-path "${MANIFEST_PATH}"
|
||||
) &
|
||||
) > >(tee -a "${API_SERVER_LOG_FILE}") 2>&1 &
|
||||
API_PID="$!"
|
||||
PIDS+=("${API_PID}")
|
||||
NAMES+=("api-server")
|
||||
|
||||
echo "[dev:rust] 等待 api-server 就绪"
|
||||
wait_for_api_server "${RUST_SERVER_TARGET}/healthz" "${API_SERVER_TIMEOUT_SECONDS}" "${API_PID}"
|
||||
wait_for_api_server "${RUST_SERVER_TARGET}/healthz" "${API_SERVER_TIMEOUT_SECONDS}" "${API_PID}" "${API_SERVER_LOG_FILE}"
|
||||
|
||||
echo "[dev:rust] 启动 vite"
|
||||
(
|
||||
|
||||
@@ -99,6 +99,7 @@
|
||||
1. 进程启动时通过 `shared-logging` 统一初始化 `tracing subscriber`。
|
||||
2. 默认日志过滤器来自 `GENARRATIVE_API_LOG`,未提供时回落到 `info,tower_http=info`。
|
||||
3. HTTP 访问日志统一通过 Axum 路由层的 `TraceLayer` 输出,后续 `request_id`、响应头与错误中间件继续在同一层扩展。
|
||||
4. 本地启动器 `npm run api-server` 和完整联调入口 `npm run dev` / `npm run dev:rust` 会在保留终端实时输出的同时,把同一份 `cargo` / `api-server` 输出持久化到 `logs/api-server/`。如需固定文件或目录,可设置 `GENARRATIVE_API_SERVER_LOG_FILE` 或 `GENARRATIVE_API_SERVER_LOG_DIR`。
|
||||
|
||||
当前 request context 约定:
|
||||
|
||||
|
||||
@@ -136,10 +136,11 @@ use crate::{
|
||||
admin_list_profile_invite_codes, admin_list_profile_redeem_codes,
|
||||
admin_list_profile_task_configs, admin_upsert_profile_invite_code,
|
||||
admin_upsert_profile_redeem_code, admin_upsert_profile_task_config,
|
||||
claim_profile_task_reward, create_profile_recharge_order, get_profile_analytics_metric,
|
||||
get_profile_dashboard, get_profile_play_stats, get_profile_recharge_center,
|
||||
get_profile_referral_invite_center, get_profile_task_center, get_profile_wallet_ledger,
|
||||
redeem_profile_referral_invite_code, redeem_profile_reward_code, submit_profile_feedback,
|
||||
claim_profile_task_reward, confirm_wechat_profile_recharge_order,
|
||||
create_profile_recharge_order, get_profile_analytics_metric, get_profile_dashboard,
|
||||
get_profile_play_stats, get_profile_recharge_center, get_profile_referral_invite_center,
|
||||
get_profile_task_center, get_profile_wallet_ledger, redeem_profile_referral_invite_code,
|
||||
redeem_profile_reward_code, submit_profile_feedback,
|
||||
},
|
||||
runtime_save::{
|
||||
delete_runtime_snapshot, get_runtime_snapshot, list_profile_save_archives,
|
||||
@@ -1488,6 +1489,12 @@ pub fn build_router(state: AppState) -> Router {
|
||||
require_bearer_auth,
|
||||
)),
|
||||
)
|
||||
.route(
|
||||
"/api/profile/recharge/orders/{order_id}/wechat/confirm",
|
||||
post(confirm_wechat_profile_recharge_order).route_layer(
|
||||
middleware::from_fn_with_state(state.clone(), require_bearer_auth),
|
||||
),
|
||||
)
|
||||
.route(
|
||||
"/api/profile/recharge/wechat/notify",
|
||||
post(handle_wechat_pay_notify),
|
||||
|
||||
@@ -10,12 +10,12 @@ use module_runtime::{
|
||||
RuntimeProfileFeedbackEvidenceSnapshot, RuntimeProfileFeedbackSubmissionRecord,
|
||||
RuntimeProfileInviteCodeRecord, RuntimeProfileMembershipBenefitRecord,
|
||||
RuntimeProfileRechargeCenterRecord, RuntimeProfileRechargeOrderRecord,
|
||||
RuntimeProfileRechargeProductRecord, RuntimeProfileRedeemCodeMode,
|
||||
RuntimeProfileRedeemCodeRecord, RuntimeProfileRewardCodeRedeemRecord,
|
||||
RuntimeProfileTaskCenterRecord, RuntimeProfileTaskClaimRecord, RuntimeProfileTaskConfigRecord,
|
||||
RuntimeProfileTaskCycle, RuntimeProfileTaskItemRecord, RuntimeProfileTaskStatus,
|
||||
RuntimeProfileWalletLedgerSourceType, RuntimeReferralInviteCenterRecord,
|
||||
RuntimeTrackingScopeKind,
|
||||
RuntimeProfileRechargeOrderStatus, RuntimeProfileRechargeProductRecord,
|
||||
RuntimeProfileRedeemCodeMode, RuntimeProfileRedeemCodeRecord,
|
||||
RuntimeProfileRewardCodeRedeemRecord, RuntimeProfileTaskCenterRecord,
|
||||
RuntimeProfileTaskClaimRecord, RuntimeProfileTaskConfigRecord, RuntimeProfileTaskCycle,
|
||||
RuntimeProfileTaskItemRecord, RuntimeProfileTaskStatus, RuntimeProfileWalletLedgerSourceType,
|
||||
RuntimeReferralInviteCenterRecord, RuntimeTrackingScopeKind,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
@@ -25,10 +25,10 @@ use shared_contracts::runtime::{
|
||||
AdminDisableProfileTaskConfigRequest, AdminUpsertProfileInviteCodeRequest,
|
||||
AdminUpsertProfileRedeemCodeRequest, AdminUpsertProfileTaskConfigRequest,
|
||||
AnalyticsBucketMetricResponse, AnalyticsMetricQueryResponse, ClaimProfileTaskRewardResponse,
|
||||
CreateProfileRechargeOrderRequest, CreateProfileRechargeOrderResponse,
|
||||
PROFILE_FEEDBACK_STATUS_OPEN, PROFILE_TASK_CYCLE_DAILY, PROFILE_TASK_STATUS_CLAIMABLE,
|
||||
PROFILE_TASK_STATUS_CLAIMED, PROFILE_TASK_STATUS_DISABLED, PROFILE_TASK_STATUS_INCOMPLETE,
|
||||
PROFILE_WALLET_LEDGER_SOURCE_TYPE_ASSET_OPERATION_CONSUME,
|
||||
ConfirmWechatProfileRechargeOrderResponse, CreateProfileRechargeOrderRequest,
|
||||
CreateProfileRechargeOrderResponse, PROFILE_FEEDBACK_STATUS_OPEN, PROFILE_TASK_CYCLE_DAILY,
|
||||
PROFILE_TASK_STATUS_CLAIMABLE, PROFILE_TASK_STATUS_CLAIMED, PROFILE_TASK_STATUS_DISABLED,
|
||||
PROFILE_TASK_STATUS_INCOMPLETE, PROFILE_WALLET_LEDGER_SOURCE_TYPE_ASSET_OPERATION_CONSUME,
|
||||
PROFILE_WALLET_LEDGER_SOURCE_TYPE_ASSET_OPERATION_REFUND,
|
||||
PROFILE_WALLET_LEDGER_SOURCE_TYPE_DAILY_TASK_REWARD,
|
||||
PROFILE_WALLET_LEDGER_SOURCE_TYPE_INVITE_INVITEE_REWARD,
|
||||
@@ -63,7 +63,10 @@ use crate::{
|
||||
http_error::AppError,
|
||||
request_context::RequestContext,
|
||||
state::AppState,
|
||||
wechat_pay::{build_wechat_payment_request, current_unix_micros, map_wechat_pay_error},
|
||||
wechat_pay::{
|
||||
WechatPayNotifyOrder, build_wechat_payment_request, current_unix_micros,
|
||||
map_wechat_pay_error,
|
||||
},
|
||||
};
|
||||
|
||||
pub async fn get_profile_dashboard(
|
||||
@@ -244,6 +247,106 @@ pub async fn create_profile_recharge_order(
|
||||
))
|
||||
}
|
||||
|
||||
pub async fn confirm_wechat_profile_recharge_order(
|
||||
State(state): State<AppState>,
|
||||
Extension(request_context): Extension<RequestContext>,
|
||||
Extension(authenticated): Extension<AuthenticatedAccessToken>,
|
||||
Path(order_id): Path<String>,
|
||||
) -> Result<Json<Value>, Response> {
|
||||
let user_id = authenticated.claims().user_id().to_string();
|
||||
let (center, order) = state
|
||||
.spacetime_client()
|
||||
.get_profile_recharge_order(order_id.clone())
|
||||
.await
|
||||
.map_err(|error| {
|
||||
runtime_profile_error_response(
|
||||
&request_context,
|
||||
map_runtime_profile_client_error(error),
|
||||
)
|
||||
})?;
|
||||
|
||||
if order.user_id != user_id {
|
||||
return Err(runtime_profile_error_response(
|
||||
&request_context,
|
||||
AppError::from_status(StatusCode::NOT_FOUND).with_message("充值订单不存在"),
|
||||
));
|
||||
}
|
||||
if order.payment_channel != PROFILE_RECHARGE_PAYMENT_CHANNEL_WECHAT_MINI_PROGRAM {
|
||||
return Err(runtime_profile_error_response(
|
||||
&request_context,
|
||||
AppError::from_status(StatusCode::BAD_REQUEST)
|
||||
.with_message("该充值订单不是微信小程序支付订单"),
|
||||
));
|
||||
}
|
||||
if order.status == RuntimeProfileRechargeOrderStatus::Paid {
|
||||
return Ok(json_success_body(
|
||||
Some(&request_context),
|
||||
ConfirmWechatProfileRechargeOrderResponse {
|
||||
order: build_profile_recharge_order_response(order),
|
||||
center: build_profile_recharge_center_response(center),
|
||||
},
|
||||
));
|
||||
}
|
||||
if order.status != RuntimeProfileRechargeOrderStatus::Pending {
|
||||
return Ok(json_success_body(
|
||||
Some(&request_context),
|
||||
ConfirmWechatProfileRechargeOrderResponse {
|
||||
order: build_profile_recharge_order_response(order),
|
||||
center: build_profile_recharge_center_response(center),
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
let wechat_order = state
|
||||
.wechat_pay_client()
|
||||
.query_order_by_out_trade_no(&order.order_id)
|
||||
.await
|
||||
.map_err(|error| {
|
||||
runtime_profile_error_response(&request_context, map_wechat_pay_error(error))
|
||||
})?;
|
||||
if wechat_order.out_trade_no != order.order_id {
|
||||
return Err(runtime_profile_error_response(
|
||||
&request_context,
|
||||
AppError::from_status(StatusCode::BAD_GATEWAY)
|
||||
.with_message("微信支付查单返回的商户订单号与本地订单不一致")
|
||||
.with_details(json!({ "provider": "wechat_pay" })),
|
||||
));
|
||||
}
|
||||
if wechat_order.trade_state != "SUCCESS" {
|
||||
return Ok(json_success_body(
|
||||
Some(&request_context),
|
||||
ConfirmWechatProfileRechargeOrderResponse {
|
||||
order: build_profile_recharge_order_response(order),
|
||||
center: build_profile_recharge_center_response(center),
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
let paid_at_micros = paid_at_micros_from_wechat_order(&wechat_order);
|
||||
let (center, order) = state
|
||||
.spacetime_client()
|
||||
.mark_profile_recharge_order_paid(
|
||||
wechat_order.out_trade_no,
|
||||
paid_at_micros,
|
||||
wechat_order.transaction_id,
|
||||
)
|
||||
.await
|
||||
.map_err(|error| {
|
||||
runtime_profile_error_response(
|
||||
&request_context,
|
||||
map_runtime_profile_client_error(error),
|
||||
)
|
||||
})?;
|
||||
|
||||
Ok(json_success_body(
|
||||
Some(&request_context),
|
||||
ConfirmWechatProfileRechargeOrderResponse {
|
||||
order: build_profile_recharge_order_response(order),
|
||||
center: build_profile_recharge_center_response(center),
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
pub async fn submit_profile_feedback(
|
||||
State(state): State<AppState>,
|
||||
Extension(request_context): Extension<RequestContext>,
|
||||
@@ -801,6 +904,15 @@ async fn resolve_wechat_identity_for_payment(
|
||||
.with_message("当前账号缺少微信小程序身份,请在小程序内重新登录后再支付"))
|
||||
}
|
||||
|
||||
fn paid_at_micros_from_wechat_order(order: &WechatPayNotifyOrder) -> i64 {
|
||||
order
|
||||
.success_time
|
||||
.as_deref()
|
||||
.and_then(|value| parse_rfc3339(value).ok())
|
||||
.map(offset_datetime_to_unix_micros)
|
||||
.unwrap_or_else(current_unix_micros)
|
||||
}
|
||||
|
||||
fn build_profile_recharge_center_response(
|
||||
record: RuntimeProfileRechargeCenterRecord,
|
||||
) -> ProfileRechargeCenterResponse {
|
||||
@@ -1260,6 +1372,7 @@ mod tests {
|
||||
let app = build_router(AppState::new(AppConfig::default()).expect("state should build"));
|
||||
|
||||
let response = app
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("GET")
|
||||
@@ -1271,6 +1384,20 @@ mod tests {
|
||||
.expect("request should succeed");
|
||||
|
||||
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
|
||||
|
||||
let confirm_response = app
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri("/api/profile/recharge/orders/rcgtest001/wechat/confirm")
|
||||
.body(Body::empty())
|
||||
.expect("request should build"),
|
||||
)
|
||||
.await
|
||||
.expect("request should succeed");
|
||||
|
||||
assert_eq!(confirm_response.status(), StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1069,10 +1069,47 @@ pub fn build_runtime_profile_recharge_order_id(
|
||||
created_at_micros: i64,
|
||||
product_id: &str,
|
||||
) -> String {
|
||||
format!(
|
||||
"recharge:{}",
|
||||
build_runtime_profile_recharge_wallet_ledger_id(user_id, created_at_micros, product_id)
|
||||
)
|
||||
// 微信支付 v3 的 out_trade_no 只接受较短的字母、数字和部分符号。
|
||||
// 订单号同时作为本地 profile_recharge_order 主键,因此统一使用可支付渠道兼容的紧凑格式。
|
||||
let timestamp = encode_runtime_profile_recharge_order_base36(created_at_micros.unsigned_abs());
|
||||
let hash = hash_runtime_profile_recharge_order_key(user_id, product_id, created_at_micros);
|
||||
format!("rcg{timestamp}{:010x}", hash & 0x0000_0003_ffff_ffff)
|
||||
}
|
||||
|
||||
fn encode_runtime_profile_recharge_order_base36(mut value: u64) -> String {
|
||||
const DIGITS: &[u8; 36] = b"0123456789abcdefghijklmnopqrstuvwxyz";
|
||||
if value == 0 {
|
||||
return "0".to_string();
|
||||
}
|
||||
|
||||
let mut buffer = Vec::new();
|
||||
while value > 0 {
|
||||
buffer.push(DIGITS[(value % 36) as usize] as char);
|
||||
value /= 36;
|
||||
}
|
||||
buffer.iter().rev().collect()
|
||||
}
|
||||
|
||||
fn hash_runtime_profile_recharge_order_key(
|
||||
user_id: &str,
|
||||
product_id: &str,
|
||||
created_at_micros: i64,
|
||||
) -> u64 {
|
||||
let mut hash = 14_695_981_039_346_656_037u64;
|
||||
for byte in user_id
|
||||
.trim()
|
||||
.as_bytes()
|
||||
.iter()
|
||||
.copied()
|
||||
.chain([b':'])
|
||||
.chain(product_id.trim().as_bytes().iter().copied())
|
||||
.chain([b':'])
|
||||
.chain(created_at_micros.to_le_bytes())
|
||||
{
|
||||
hash ^= u64::from(byte);
|
||||
hash = hash.wrapping_mul(1_099_511_628_211);
|
||||
}
|
||||
hash
|
||||
}
|
||||
|
||||
pub fn resolve_runtime_profile_points_recharge_delta(
|
||||
|
||||
@@ -242,6 +242,14 @@ pub fn build_runtime_profile_recharge_center_get_input(
|
||||
Ok(RuntimeProfileRechargeCenterGetInput { user_id })
|
||||
}
|
||||
|
||||
pub fn build_runtime_profile_recharge_order_get_input(
|
||||
order_id: String,
|
||||
) -> Result<RuntimeProfileRechargeOrderGetInput, RuntimeProfileFieldError> {
|
||||
let order_id =
|
||||
normalize_required_string(order_id).ok_or(RuntimeProfileFieldError::MissingOrderId)?;
|
||||
Ok(RuntimeProfileRechargeOrderGetInput { order_id })
|
||||
}
|
||||
|
||||
pub fn build_runtime_profile_recharge_order_create_input(
|
||||
user_id: String,
|
||||
product_id: String,
|
||||
|
||||
@@ -1060,6 +1060,12 @@ pub struct RuntimeProfileRechargeCenterGetInput {
|
||||
pub user_id: String,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "spacetime-types", derive(SpacetimeType))]
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct RuntimeProfileRechargeOrderGetInput {
|
||||
pub order_id: String,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "spacetime-types", derive(SpacetimeType))]
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct RuntimeProfileRechargeOrderCreateInput {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user