Compare commits

..
16 Commits
Author SHA1 Message Date
super 6320967c2b docs(readme): 更新中英文 NovaLink 功能介绍 2026-12-05 15:16:57 +08:00
super 98df62db7d merge: 同步 new-api 上游至 080997bf2 2026-12-05 14:25:19 +08:00
super 3f8211f1cd feat(support): 新增独立举报工单分类 2026-12-05 13:48:19 +08:00
super 0e5670c717 Merge branch 'dev/novalink-payment-lifecycle' into dev/novalink-release-v1.13.0 2026-12-05 00:49:57 +08:00
super add4917103 feat(payment): 统一网关凭据加密与启停管理 2026-12-05 00:49:56 +08:00
super 0de65f5947 Merge branch 'dev/novalink-alipay-docker' into dev/novalink-release-v1.13.0 2026-12-05 00:49:29 +08:00
super 4242f50b94 docs(deploy): 配置统一支付密钥与部署说明 2026-12-05 00:48:26 +08:00
super 623802c02c feat(keys): 更新 CC Switch 与聊天客户端一键导入 2026-12-05 00:05:06 +08:00
Calcium-Ion 080997bf23 fix(relay): Claude 流开始输出后不再换渠道重试,上游 error 转给客户端 (#8550)
上游在流中途发来 error 事件(如 overloaded_error)时,HandleStreamResponseData
返回 500。重试判断不知道这次尝试已经给客户端写过事件,换渠道重来,新流接在
半截旧流后面,客户端看到两个 message_start;全部失败时还会再补一个 error。

- 还没有事件写给客户端:照旧可以重试。
- 已写出事件但没有输出:不重试,由 relay 在同一条流里发 error 并退款。
- 已有输出:不重试,error 事件转给客户端(保留上游 type 和 message),
  已送达的输出按上游报告的 usage 计费,没报告则按估算。
- Claude 转 Responses:发出 response.failed 后同样只为已送达的输出计费,
  没有输出不收费,流状态记为失败。

controller 的 writeRelayStreamError 移到 helper.StreamErrorData,供 Claude
处理器复用。
2026-12-03 18:34:34 +08:00
Seefs 5911c8cca8 fix(middleware): abort canceled Redis rate-limit checks with 499 (#8512)
Treat Redis rate-limit failures as client-closed (HTTP 499, no error log) only when both the Redis error and request context report context.Canceled, while keeping deadline timeouts and Redis failures fail-closed with HTTP 500.

Closes #8462
2026-12-02 19:06:23 +08:00
Seefs 5f56c685d4 fix(gemini): emit stream finish_reason only in dedicated terminal chunk (#8522)
Stop setting finish_reason=tool_calls unconditionally on every Gemini stream chunk containing a functionCall, omit empty content strings on non-text chunks, and strip upstream finish reasons from payload chunks so GeminiChatStreamHandler and GeminiToChatStreamState emit finish_reason once in an empty-delta terminal chunk.
2026-12-02 19:03:33 +08:00
Seefs 16369071a1 fix(relay): normalize /pg/ playground path for route matching (#8534)
Playground sends chat completions to /pg/chat/completions while GenRelayInfo maps info.RequestURLPath to /v1/chat/completions. Distributor path filters, per-route pass-through lookup in InitChannelMeta, and route resolution in the advanced custom and provider plugin adaptors still read raw c.Request.URL.Path, rejecting advanced custom, vLLM/SGLang preset, and provider plugin channels in Playground.

Add common.NormalizeRelayPath to map /pg/... paths onto /v1/... at the route matching and provider plugin hook boundaries while keeping c.Request.URL.Path unchanged for Playground detection, group selection, and request logs.

Closes #5966
2026-12-02 15:42:41 +08:00
Seefs 1c0b4d6471 fix(billing): cap subscription usage at settlement instead of rejecting overrun (#8523)
* fix(billing): cap subscription usage at settlement instead of rejecting overrun

When a post-request settlement delta exceeds the remaining subscription quota,
PostConsumeUserSubscriptionDelta rejects the whole update and leaves
amount_used below amount_total. Subsequent requests with small pre-consume
estimates keep passing admission and become free, and secondary subscriptions
are never selected.

Add model.SettleUserSubscriptionDelta to cap positive settlement charges at
AmountTotal (or math.MaxInt64 for unlimited plans), log the uncovered
remainder, and return the applied delta. Route SubscriptionFunding.Settle and
async task settlement to it while keeping PostConsumeUserSubscriptionDelta
strict for reservations and Realtime in-session metering, and without changing
the FundingSource interface signature.

* test(billing): add regression coverage for capped subscription settlement

Consolidate regression cases in service/subscription_settle_test.go covering SettleUserSubscriptionDelta finite capping, unlimited MaxInt64 saturation, refund zero-flooring, BillingSession dual-subscription exhaustion and switching, strict PostConsumeQuota rejection for Realtime in-session metering, and async RecalculateTaskQuota overrun capping.
2026-12-02 15:11:32 +08:00
Hao Wang 0d0d396f48 fix(task): find unfinished tasks through the status index (#8529)
HasUnfinishedSyncTasks, GetAllUnFinishSyncTasks and GetTimedOutUnfinishedTasks
exclude the two terminal statuses with "status != ?" or "NOT IN". PostgreSQL
and SQLite cannot use idx_tasks_status for that filter, so every check reads
all finished tasks. The async_task_poll scheduler runs the existence check
every 15 seconds. On a PostgreSQL table with 1.4 million finished tasks, one
check took about 27 seconds, and the database kept scanning the table even
when no task was unfinished.

Write the filter as the key ranges around FAILURE and SUCCESS. It matches the
same rows, and all three databases answer it from the status index.

Closes #8528
2026-12-02 14:45:40 +08:00
coderwhq b697786325 fix(openai): record first response time on first non-empty stream output (#8531) 2026-12-02 14:05:07 +08:00
Seefs f0c94957fd fix(channels): enable VolcEngine upstream model discovery (#8306) 2026-12-02 13:52:23 +08:00
102 changed files with 4338 additions and 1125 deletions

No files matched your search

+3
View File
@@ -3,6 +3,9 @@
*.md
.vscode
.gitignore
# Keep runtime secrets out of the Docker build context, including with COPY . .
**/.env
**/.env.*
Makefile
docs
.eslintcache
+26 -19
View File
@@ -25,11 +25,12 @@
# 数据库相关配置
# 启用错误日志记录
# ERROR_LOG_ENABLED=true
# 数据库连接字符串
# 数据库连接。使用仓库的正式 Compose 时,在其 environment 列表设置数据库连接和 Redis 地址
# 升级时沿用原连接与数据卷。默认 PostgreSQL 的密码需与 Compose 的 POSTGRES_PASSWORD 一致
# SQL_DSN=user:password@tcp(127.0.0.1:3306)/dbname?parseTime=true
# 日志数据库连接字符串
# 仅使用独立日志库时设置。迁移时单独备份该库
# LOG_SQL_DSN=user:password@tcp(127.0.0.1:3306)/logdb?parseTime=true
# SQLite数据库路径
# 使用 SQLite 时保留原数据库文件。在容器内将其放在持久化挂载目录,例如 /data
# SQLITE_PATH=/path/to/sqlite.db
# 数据库最大空闲连接数
# SQL_MAX_IDLE_CONNS=100
@@ -99,14 +100,20 @@
# Gemini 识别图片 最大图片数量
# GEMINI_VISION_MAX_IMAGE_NUM=16
# 会话密钥
# SESSION_SECRET=random_string
# 上游监控凭据使用独立的 AES-256-GCM 密钥(32 字节随机值的 Base64);不要与数据库一同保存
# 必须在所有节点配置相同且持久的密钥,修改前先迁移已保存凭据
# UPSTREAM_MONITOR_KEY=base64_encoded_32_random_bytes
# 官方支付宝商户凭据使用独立的 AES-256-GCM 密钥,所有后端节点使用同一持久密钥
# 密钥与数据库分别备份,旧订单查单及回调处理依赖此密钥
# ALIPAY_DIRECT_KEY=base64_encoded_32_random_bytes
# 持久密钥(详见 README 的「部署时需要保留的配置」)。实际值只写入部署用 .env 或密钥管理系统
# 生产单节点和多节点均应设置 SESSION_SECRET。首次生成:openssl rand -hex 32
# 所有后端节点用同一个值。留空时每次启动会生成临时值,换值后现有登录会话失效
SESSION_SECRET=
# 用于缓存摘要和任务附件签名,留空时沿用 SESSION_SECRET。已有独立值时应保留
# 共享 Redis 或共同处理任务附件的后端节点使用同一个有效值
CRYPTO_SECRET=
# 启用上游监控时设置,用于加密上游站点凭据。首次生成:openssl rand -base64 32
UPSTREAM_MONITOR_KEY=
# 使用任一支付网关时设置,用于加密当前凭据和历史订单的凭据版本。首次生成:openssl rand -base64 32
PAYMENT_CREDENTIAL_KEY=
# 两个功能密钥分别生成并与数据库分开备份。已有凭据时沿用原值,丢失或替换后无法解密旧凭据
# Docker Compose 将上述变量注入 new-api 容器,更新值后要重建容器
# 登录密码请求体 RSA-OAEP 加密;默认关闭,且不能替代 HTTPS
# PASSWORD_LOGIN_ENCRYPTION_ENABLED=true
@@ -116,12 +123,11 @@
# v2 login-password envelope support (when login encryption is enabled).
# Existing bcrypt hashes and MFA backup codes are not rewritten.
# ACCOUNT_PASSWORD_HASH_ALGORITHM=argon2id
# false/未配置:本地 HTTP 模式,关闭 refresh/logout OriginGuard,且不得设置 TRUSTED_URL;兼容本地开发代理。
# true:启用 Secure Refresh Cookie 和严格 OriginGuard,必须同时列出全部可信 HTTPS Origin。
# SESSION_COOKIE_TRUSTED_URL 多项用英文逗号分隔;不支持通配符、路径或域名后缀匹配。
# 这些设置不修改 relay CORS。
# SESSION_COOKIE_SECURE=false
# SESSION_COOKIE_TRUSTED_URL=https://example.com,https://admin.example.com
# 正式 Compose 从 .env 读取以下两项。本地 HTTP 开发用 false,且留空可信源
# 公网 HTTPS 部署设为 true,同时填所有可信的精确 HTTPS Origin,多个用英文逗号分隔
# 可信源包含协议、域名和非标准端口,不写路径或通配符。这些设置不修改 relay CORS
SESSION_COOKIE_SECURE=false
SESSION_COOKIE_TRUSTED_URL=
# 每用户最多保留的活跃登录 Session
# USER_SESSION_ACTIVE_LIMIT=50
# 单用户在签发窗口内允许创建的 Session 总数(包含已撤销)
@@ -149,9 +155,10 @@
LINUX_DO_TOKEN_ENDPOINT=https://connect.linux.do/oauth2/token
LINUX_DO_USER_ENDPOINT=https://connect.linux.do/api/user
# 节点类型
# 如果是主节点则为master
# 节点角色和审计名称。生产 Compose 默认 master,多节点保留一个 master,其余设置 slave
# 每个节点设置不同的 NODE_NAME,在重建容器时保留该节点原来的名称
# NODE_TYPE=master
# NODE_NAME=new-api-node-1
# 可信任重定向域名列表(逗号分隔,支持子域名匹配)
# 用于验证支付成功/取消回调URL的域名安全性
+1 -1
View File
@@ -23,7 +23,7 @@ This is an AI API gateway/proxy built with Go. It aggregates 40+ upstream AI pro
- Reward operations pause, resume, cancel or retry only unpaid gifts with a versioned CAS and an exact-reward root-session proof. Manual actions retain exact-operation authorization and never bypass due dates, disabled accounts, explicit earnings holds, or wallet limits. Archived registration scores and review hashes do not trigger automatic review or blocking. Queued gifts use their original amounts and due dates. Serialize payouts with participant and reward row locks, acquiring SQLite’s writer lock before reading. Manual grants remain non-purchase principal and do not increase purchase or consumption credit. Balance cache delivery uses durable prepared/applied operations and must preserve pending reservations across response loss, retries and cold-cache hydration; hold the same user lock through reading SQL and populating Redis. Optional hashes use variable-length storage so PostgreSQL padding cannot turn missing evidence into a signal. Health alerts stay inside the operations panel, and policy impact previews must remain read-only without initializing profiles or enforcing account changes.
- Referral earnings use independent primary-database accounts, events, rewards and withdrawal entries in `model/user_referral*.go` and `model/user_withdrawal.go`. The versioned referral policy selects one mode: off, purchase cashback, or consumption commission. Freeze each order's classification at wallet credit and retain its original terms for later verification and settlement. A cashback order cannot earn consumption commission. In consumption mode, only finalized wallet usage funded by eligible verified external wallet credits creates commission. While another mode is active, such usage creates no commission. Off pauses new earnings and preserves still-open lot eligibility. Switching to purchase cashback closes all still-open consumption lots after a root browser session confirms a signed financial preview and overlapping wallet holds finish. The cutover transaction snapshots each lot’s remaining eligible principal and closes eligibility without reducing the buyer’s wallet. Use the lot’s frozen percentage and delay from the actual cutover time, and keep re-entry to consumption commission locked until every positive cutover amount is released or reconciled to zero. Exact purchase corrections preserve cutover principal provenance through later wallet spending and refunds. Store and display historical earnings by their original basis and support reconciliation by the authorized recharge lot ID. Spend other wallet quota first, then verified lots in credit order. At verified initial wallet credit, freeze the direct inviter, policy version, level, percentage and delay on the recharge lot before counting its own contribution. Serialize credits and purchase corrections per inviter. At final consumption, calculate each lot's commission from the original snapshot and start its release delay. Never reconstruct missing snapshots from the current level. Opening balances, grants, redemptions, transfers, subscriptions and debt are excluded. Refund only the matching purchase or settled usage allocation and preserve existing withdrawal facts. Before upgrading a shared database, drain and stop old-version wallet writers. The master initializes durable wallet accounting during ordinary startup and other nodes load the same epoch. Startup never enables referral earnings or sets a policy activation time. The authenticated policy save publishes the mode and its effective time, and versioned policy locking determines recharge attribution. The original opt-in epoch can still interpret mode-less historical policies. Keep unfinished usage coverage and cache delivery records for the existing reconciliation paths. Persisted older policies inherit their original global delay when level delays are absent; duplicate historical contribution thresholds select the earliest level, while new saves require increasing contribution requirements. Never reprice already determined rewards. Old `aff_quota` remains non-withdrawable gift quota. Transfers and withdrawals consume the same new available balance with persistent request idempotency; a withdrawal freezes its quota and snapshots the site's `USDExchangeRate` and CNY amount. Root-only manual payouts require an assigned operator, exact-operation session proof, versioned transition and unique payment reference. Never automatically release `paying` funds or rewrite paid facts on refund; reversals retain recovery debt and block further spending until resolved. Plaintext payout details must not enter logs or administrator list responses.
- Reward policy edits use whole minutes while persisted delays and historical payout timestamps retain exact seconds. Record each published referral mode change in the policy transaction with the saved version and authenticated actor. Import old transitions only from verifiable policy or cutover facts. Reward policy and withdrawal forms show amounts in the site's display currency, fall back to USD in Token mode, and map edits to integer wallet quota. Withdrawal payouts use the server's CNY quote at the site exchange rate.
- Payment gateway availability is server-owned. Epay channel codes belong to Epay, and removing channels stops new orders while existing orders retain callback handling with the configured signing credentials. Direct Alipay orders reserve integer CNY cents transactionally against a seller's Beijing-day paid totals and outstanding reservations, shared across the seller's apps in the same environment. Freeze merchant credential revision, return and notify addresses, expiry, and purchase terms. A checkout issued to one merchant can release its reservation only on verified terminal evidence, or after signed expiry and a verified absent trade. Retain late payments even after local closure. Verify signed notifications and query results with the original app. New payment orders wait for the configured initial query delay while pending, and manual checks share the provider-query lease without changing the automatic schedule. Resolving an Alipay trade number must bind the signed merchant order number to the original local merchant and credential revision before applying evidence. Sandbox tests can omit notification and return URLs when no HTTPS site address is configured. Remove merchants with no orders and their unused credentials under the same configuration lock as order creation. Archive merchants with order history, preserving their identities and credential revisions for reconciliation. Archiving excludes them from routing, and restoring brings them back disabled. Preserve provider-confirmed payment, refund, and entitlement delivery facts separately. Never use an order total as a substitute for unknown merchant proceeds. Sandbox orders cannot create production receipts or entitlements. Store `ALIPAY_DIRECT_KEY` separately from the database.
- Payment gateway availability is server-owned. Epay channel codes belong to Epay, and removing channels stops new orders while existing orders retain callback handling with the configured signing credentials. Direct Alipay orders reserve integer CNY cents transactionally against a seller's Beijing-day paid totals and outstanding reservations, shared across the seller's apps in the same environment. Freeze merchant credential revision, return and notify addresses, expiry, and purchase terms. A checkout issued to one merchant can release its reservation only on verified terminal evidence, or after signed expiry and a verified absent trade. Retain late payments even after local closure. Verify signed notifications and query results with the original app. New payment orders wait for the configured initial query delay while pending, and manual checks share the provider-query lease without changing the automatic schedule. Resolving an Alipay trade number must bind the signed merchant order number to the original local merchant and credential revision before applying evidence. Sandbox tests can omit notification and return URLs when no HTTPS site address is configured. Remove merchants with no orders and their unused credentials under the same configuration lock as order creation. Archive merchants with order history, preserving their identities and credential revisions for reconciliation. Archiving excludes them from routing, and restoring brings them back disabled. Preserve provider-confirmed payment, refund, and entitlement delivery facts separately. Never use an order total as a substitute for unknown merchant proceeds. Sandbox orders cannot create production receipts or entitlements. Store `PAYMENT_CREDENTIAL_KEY` separately from the database.
- `relaykit/` is an independent Go module for protocol DTOs and conversions; transport, authentication, database access, and billing stay in the host.
- `tokenkit/` is an independent Go module for text and image token counting and estimation; request parsing, file loading, and billing stay in the host.
- `pluginkit/` is an independent Go module for the plugin API v1 contract, its documents, the plugin utilities and the moejs execution layer; `pkg/jsplugin/` keeps the registry, routing and CLI and re-exports pluginkit's names.
+91
View File
@@ -1,3 +1,94 @@
# NovaLink New API
NovaLink builds on [QuantumNous/new-api](https://github.com/QuantumNous/new-api) and adds upstream cost analysis, user operations, referral payouts, site documentation, and support tickets for gateway operators.
[Live gateway](https://newapi.it120.cloud) · [NovaLink releases](https://github.com/zsz2018/NovaLink-new-api/releases) · [Report an issue](https://github.com/zsz2018/NovaLink-new-api/issues) · [简体中文](./README.md)
[Upstream monitoring](#novalink-monitor) · [User operations](#novalink-operations) · [Referral commissions](#novalink-referrals) · [Site documentation](#novalink-docs) · [Support tickets](#novalink-support) · [Client integrations](#novalink-extras) · [Console locations](#novalink-entries) · [Deployment](#novalink-deployment) · [Upstream project](#upstream-reference)
<a id="novalink-monitor"></a>
### Upstream monitoring and margin comparison
- Manage upstream sites and accounts, currencies, exchange rates, and top-up conversion settings. The server encrypts stored credentials. Administrators can check whether paired browsers are online and revoke device access.
- Pair the separate NovaLink Browser Bridge extension to record browser steps, map response fields, and preview the results. Run collections manually or on an account schedule, resume after manual verification, and review diagnostics and historical snapshots.
- Collect account identity, balances, groups, and multipliers from authorized upstream browser sessions, with optional model prices and top-up records. Use the New API or Sub2API adapter, or configure field mappings for other sites with optional AI assistance. The extension sends structured results and keeps raw responses in memory for the duration of the task.
- Configure one backup address per site. If the primary becomes unavailable during a task, collection can switch once and authenticate again at the backup. The operator confirms before the task repeats actions other than login or requests that are not read-only. Snapshots record the address used for collection.
- Map local models and groups to upstream procurement channels and compare selling prices with procurement costs for the same usage scenario. The comparison supports token, per-request, tiered, and supported native pricing expressions. Administrators can opt in to reviewed reference prices when procurement quotes are missing.
> Upstream monitoring and the browser extension are still in development. Collection requires a matching extension, `UPSTREAM_MONITOR_KEY`, and device pairing by a root administrator.
<a id="novalink-operations"></a>
### User operations and contribution levels
- Track activity, registration conversion, first and repeat purchases, wallet balances, debt, and usage and invitation rankings. Reports show verified payments by provider, payment method, and original currency. Day 1, 7, and 30 usage retention includes users whose measurement dates have ended and have complete usage records.
- Annual contribution levels count 100% of a user's verified net external wallet top-ups and 50% of the equivalent top-ups made by their direct referrals. Contributions count for 365 days from credit. Automatic levels are reviewed on January 1 in Beijing time, and users can earn upgrades during the year.
- Configure separate rewards for first purchases and first subscriptions. Wallet top-ups and eligible redemption codes share one lifetime first-purchase reward. Registration and invitation rewards are issued immediately, with separate amounts for the inviter and invitee.
- Root administrators can manage contribution levels and earnings holds, and pause, resume, cancel, or retry rewards that have yet to be issued. Administrators can search users and usage logs by exact user ID and bulk-enable, disable, or add quota to users. The margin comparison can also show an operating net profit estimate based on the last 30 complete Beijing calendar days.
<a id="novalink-referrals"></a>
### Referral commissions and withdrawals
- Choose between pausing new commissions, earning commission on eligible direct referrals' wallet purchases, or earning commission as direct referrals spend eligible verified wallet credits.
- Each eligible wallet credit retains its referral relationship, policy, level, commission rate, and release delay at the time of credit. Users can view pending, available, and held earnings, as well as commission and withdrawal history.
- When switching from consumption to purchase commissions, a root administrator can preview and confirm settlement of the remaining eligible credits under their original terms. The buyer keeps those credits available in their wallet.
- Users can move available earnings to their spending wallet or request a withdrawal. A withdrawal holds the required balance and locks the CNY quote. A root administrator claims the request, makes the manual payout, and records its payment reference.
> Weighted contribution levels require a root administrator to publish an enabled multi-level policy. New commissions, first-purchase rewards, first-subscription rewards, and withdrawals are off by default.
<a id="novalink-docs"></a>
### Site documentation
- Visitors can browse published Markdown articles at `/docs`, search by title or group, and switch articles in the same reader. The reader includes a mobile table of contents, heading navigation, and controls to copy section links and code snippets.
- Root administrators can manage document groups and ordering, preview edits, save drafts, publish articles, and unpublish them. Readers see the last published version while drafts are being edited. Article URLs stay fixed after first publication.
<a id="novalink-support"></a>
### Support tickets and reports
- Signed-in users can open tickets about API errors, accounts, payments, feature requests, and reports. API error tickets can link to a request record. Users can track progress and reply within an open ticket.
- Administrators can filter by category or status, reply, mark tickets complete, close them, and reopen them. Sidebar badges show tickets waiting for a reply and notify users when their tickets are completed.
<a id="novalink-extras"></a>
### Client integrations and maintenance
- Pin up to three chat presets as API key import shortcuts. The full preset list remains available in the menu, and administrators can edit presets visually or in JSON.
- Import an API key configuration into CC Switch for clients such as Claude Code, Codex, and Gemini CLI. Choose the app, name the configuration, and select a model if needed. Confirm the import in CC Switch v4.0.47 or later.
- Fetch the upstream model list when creating or editing a VolcEngine channel, then choose which models to enable.
- Read full multiline API key group descriptions in the picker and after selecting a group. Administrators can check the current NovaLink version and open the release notes from the console header.
<a id="novalink-entries"></a>
### Console locations
| Task | Location | Access |
| --- | --- | --- |
| Configure upstream collection and compare margins | Upstream Monitoring · `/upstream-monitor` | Root administrator |
| Review user operations and manage rewards or withdrawals | User Management → Operations Overview · `/users` | Administrators with access. Configuration and payouts require a root administrator |
| Review contribution levels, commissions, and withdrawals | Wallet → Referral Program · `/wallet` | Signed-in users |
| Search and read published documentation | Site Documentation · `/docs` | Visitors and signed-in users |
| Edit and publish documentation | Site & Branding → Site Documentation · `/system-settings/site/docs` | Root administrator |
| Submit tickets and view replies | My Tickets · `/support-tickets` | Signed-in users |
| Review and handle tickets | Ticket Management · `/admin/support-tickets` | Administrator |
| Configure API key import shortcuts | System Settings → Content → Chat Presets · `/system-settings/content/chat` | Root administrator |
| Import into CC Switch or use chat presets | API Keys · `/keys` | Signed-in users |
<a id="novalink-deployment"></a>
### Deploy NovaLink
Download the Windows x64 package from [NovaLink releases](https://github.com/zsz2018/NovaLink-new-api/releases), or build from this repository. For Docker, run `docker build -t novalink-new-api:local .` in the repository root, then set the `new-api` service's image in the [Compose configuration](./docker-compose.yml) to `novalink-new-api:local`.
The [NovaLink deployment guide in Chinese](./README.md#novalink-deployment) covers configuration to preserve across upgrades, the shared payment credential key, and Alipay AI Pay setup and migration.
---
<a id="upstream-reference"></a>
<div align="center">
![new-api](/web/public/logo.png)
+59 -8
View File
@@ -13,7 +13,7 @@ NovaLink 基于 [QuantumNous/new-api](https://github.com/QuantumNous/new-api)
[本仓库](https://github.com/zsz2018/NovaLink-new-api) · [NovaLink 版本发布](https://github.com/zsz2018/NovaLink-new-api/releases) · [问题反馈](https://github.com/zsz2018/NovaLink-new-api/issues) · [English](./README.en.md)
[上游监控与利润比较](#novalink-monitor) · [用户运营](#novalink-operations) · [返佣与提现](#novalink-referrals) · [站内文档](#novalink-docs) · [其他改进](#novalink-extras) · [使用入口](#novalink-entries) · [部署](#novalink-deployment) · [上游资料](#upstream-reference)
[上游监控与利润比较](#novalink-monitor) · [用户运营](#novalink-operations) · [返佣与提现](#novalink-referrals) · [站内文档](#novalink-docs) · [客服工单](#novalink-support) · [其他改进](#novalink-extras) · [使用入口](#novalink-entries) · [部署](#novalink-deployment) · [上游资料](#upstream-reference)
</div>
@@ -28,6 +28,7 @@ NovaLink 基于 [QuantumNous/new-api](https://github.com/QuantumNous/new-api)
- **集中管理上游站点和账号**,维护币种、汇率及充值折算参数。服务端加密保存登录凭据,控制台可查看浏览器在线状态并撤销设备授权。
- **录制并执行浏览器采集流程**。配对独立的 NovaLink Browser Bridge 扩展后,在侧栏录制页面操作、配置字段映射并预览结果。控制台支持手动采集、按账号定时采集、人工验证后继续、取消、重试,以及查看任务诊断和历史快照。
- **从已授权登录的上游页面采集数据**,包括账号身份、余额、分组和倍率,以及可选的模型价格与充值记录。提供 New API、Sub2API 专用适配器及普通站点字段映射,支持分页、跨响应取值和嵌套分组模型列表。扩展向本站回传结构化结果,原始响应仅在当次任务的扩展内存中使用。
- **采集主备切换**。站点可配置一个备用地址。主站不可用时,正在执行的任务可切换一次,在备用站点重新认证并采集。重做已发出的非登录操作或非只读请求前,需管理员确认。采集快照会记录实际使用的站点。
- **按需使用 AI 辅助配置**普通站点的字段映射。管理员预览验证并确认保存后,后续采集直接执行已保存的规则。
- **从本地分组快捷绑定采购渠道**,可选择上游账号及分组、查看已采集的分组倍率、批量绑定本地模型或指定单个模型的对应关系。
- **在同一用量场景中比较售价和采购成本**,可调整输入、输出、缓存读写 Token 和请求次数。支持按 Token、按次、阶梯价格及受支持的原生计费表达式,纳入汇率、分组倍率、充值折算及双方费率设置。可筛选亏损线路,查看毛利、毛利率、成本数据覆盖率,以及按阶梯和计费项拆分的明细。
@@ -66,15 +67,24 @@ NovaLink 基于 [QuantumNous/new-api](https://github.com/QuantumNous/new-api)
### 站内文档中心
- **公开阅读**。访客可从站点导航进入 `/docs`,按分组浏览已发布的 Markdown 文章。阅读页支持移动端目录、正文标题导航、复制章节链接及代码片段。
- **公开阅读与搜索**。访客可从站点导航进入 `/docs`,按分组浏览已发布的 Markdown 文章,也可按标题或分组搜索并直接打开结果。可在同一阅读页切换文章。阅读页支持移动端目录、正文标题导航、复制章节链接及代码片段。
- **目录与文章管理**。在站点与品牌设置中维护文档分组、文章归属和展示顺序。编辑工作区提供实时预览、全页预览、保存草稿、发布和下架。
- **草稿与发布快照分别保存**。保存草稿后,读者仍可访问上次发布的版本。首次发布后文章地址固定,目录调整可以单独保存。
<a id="novalink-support"></a>
### 客服工单与举报
- **我的工单**支持提交 API 错误、账号、支付、功能建议和举报等问题。提交 API 错误时可关联请求记录。用户可在工单内查看进度并继续回复。
- **工单管理**支持按分类和状态筛选、回复、标记完成、关闭和重新打开。侧栏提醒显示待回复工单,用户也会收到工单完成提醒。
<a id="novalink-extras"></a>
### 客户端接入与维护改进
- **API 密钥导入快捷按钮**支持从聊天预设中设置图标并勾选最多 3 项,按预设顺序直接显示在密钥列表。其余预设仍可从菜单打开。设置支持可视化编辑和 JSON 编辑。
- **一键导入 CC Switch**。从 API 密钥列表选择 Claude Code、Codex、Gemini CLI 等应用,填写配置名称并按需选择模型,再打开 CC Switch 确认导入。需要 CC Switch v4.0.47 或更新版本。
- **火山引擎模型获取**。新建或编辑火山引擎渠道时,可从上游获取模型列表并选择要启用的模型。
- **API 密钥分组描述**在候选列表和选中后均可完整显示,保留多行说明并自动换行。
- **NovaLink 版本检查**让管理员从控制台顶部查看当前版本、检查本分支发布并打开发布说明。普通登录用户在此位置可打开本分支仓库,错误页面也提供本分支的问题反馈入口。
- **NovaLink 图标**应用于 Web 标志、浏览器标签和 Electron 桌面应用与托盘。
@@ -90,10 +100,12 @@ NovaLink 基于 [QuantumNous/new-api](https://github.com/QuantumNous/new-api)
| 上游采集、配置与利润对比 | 上游监控 · `/upstream-monitor` | 超级管理员 |
| 用户运营、奖励记录与提现处理 | 用户管理 → 运营概览 · `/users` | 管理员查看获授权的数据,超级管理员可配置和处理提现 |
| 等级进度、推广佣金和提现申请 | 钱包 → 推荐计划 · `/wallet` | 登录用户 |
| 阅读已发布的文档 | 站点文档 · `/docs` | 访客与登录用户 |
| 搜索和阅读已发布的文档 | 站点文档 · `/docs` | 访客与登录用户 |
| 编辑和发布文档 | 站点与品牌 → 站点文档 · `/system-settings/site/docs` | 超级管理员 |
| 提交工单或举报、查看回复 | 我的工单 · `/support-tickets` | 登录用户 |
| 筛选和处理工单 | 工单管理 · `/admin/support-tickets` | 管理员 |
| 配置密钥导入快捷按钮 | 系统设置 → 内容 → 聊天预设 · `/system-settings/content/chat` | 超级管理员 |
| 使用密钥导入快捷按钮 | API 密钥 · `/keys` | 登录用户 |
| 导入 CC Switch 或使用聊天预设 | API 密钥 · `/keys` | 登录用户 |
<a id="novalink-deployment"></a>
@@ -101,11 +113,50 @@ NovaLink 基于 [QuantumNous/new-api](https://github.com/QuantumNous/new-api)
使用 [NovaLink 发布页](https://github.com/zsz2018/NovaLink-new-api/releases)中与部署平台匹配的产物,或从本仓库源码构建。使用 Docker 可在仓库根目录执行 `docker build -t novalink-new-api:local .`,然后将 [Compose 配置](./docker-compose.yml) 中 `new-api` 服务的 `image` 改为该本地镜像。下方上游快速开始中的 `calciumion/new-api:latest` 提供 New API 的上游功能。
安装上游采集功能时,为所有后端节点配置同一持久 `UPSTREAM_MONITOR_KEY`。首次配置可用 `openssl rand -base64 32` 生成密钥,密钥与数据库分别备份。已保存凭据的实例应继续使用原密钥。升级复用同一数据库的部署时,先备份数据,并停止旧版本中仍在处理钱包写入的实例。
#### 部署时需要保留的配置
官方支付宝在「系统设置 → 计费 → 支付网关 → 支付宝(AI付)」配置。启用正式收款前配置公网 HTTPS 站点地址,为每个后端节点设置同一持久的 `ALIPAY_DIRECT_KEY`。可用 `openssl rand -base64 32` 生成密钥,并与数据库分别备份。每个生产商户需开通对应支付宝产品。网页收款可使用支付宝收银台,站内二维码需要当面付权限,嵌入式付款页需要在实际站点和商户下验证。
首次部署可从 [.env.example](./.env.example) 复制一份部署用 `.env`。已有部署在原文件中逐项补齐,升级、恢复或迁移时带上原有配置。仓库的 [正式 Compose 模板](./docker-compose.yml) 和 [开发 Compose 模板](./docker-compose.dev.yml) 都会从 `.env` 向应用容器传入下表的四个密钥。自建 Compose 文件也需要在 `environment` 中显式映射所用变量。若终端中已导出同名变量,Compose 会优先使用终端里的值。
支付宝付款通知通过 `/api/alipay-direct/notify` 接收。订单超过「自动查单延迟」仍待支付时,后台会向支付宝查询,默认延迟 5 分钟。管理员也可在「支付宝订单」按站内订单号或支付宝交易号主动查单。用尚未同步的支付宝交易号查询时,需选中该笔交易的商户。订单列表显示首次确认支付的来源(验签回调或验签查单)。沙箱订单可在后台独立发起,本地没有 HTTPS 站点地址时可通过主动查单确认支付。沙箱订单不会增加正式钱包余额或套餐权益。
| 密钥 | 什么时候需要 | 重启、升级与多节点 |
| --- | --- | --- |
| `SESSION_SECRET` | 生产环境单节点和多节点都应设置。首次可用 `openssl rand -hex 32` 生成 | 所有节点使用同一个值。留空时每次启动生成临时值,改值会使现有登录和临时鉴权凭证失效 |
| `CRYPTO_SECRET` | 可留空,程序默认沿用 `SESSION_SECRET`。已有单独配置时保留原值 | 共用 Redis 或共同处理任务附件的节点使用相同的有效值。变更会使旧缓存摘要和已签发的任务附件链接失效 |
| `UPSTREAM_MONITOR_KEY` | 启用上游监控时配置,用于加密站点凭据。首次运行 `openssl rand -base64 32` | 继续使用同一批凭据的实例必须沿用原值,否则无法解密 |
| `PAYMENT_CREDENTIAL_KEY` | 使用任一支付网关(含支付宝 AI付沙箱)时配置,用于加密当前及历史支付凭据。首次另行运行 `openssl rand -base64 32` | 继续使用同一数据库的节点沿用原值。丢失或替换会影响收款、历史订单查单和回调 |
两个功能密钥各自独立生成,保留完整 Base64 输出和末尾的 `=`。密钥与数据库分别备份,部署用 `.env` 保存在受限位置。
| 部署配置 | 怎么填和怎么保留 |
| --- | --- |
| `SQL_DSN`、`SQLITE_PATH`、`LOG_SQL_DSN` | 保留主库连接和数据卷。未设 `SQL_DSN` 时使用 SQLite,保留原 SQLite 数据文件和路径。配置了独立日志库时单独备份该库。多个应用节点共用同一个主数据库 |
| `REDIS_CONN_STRING` | 使用 Redis 时保存原连接配置。Compose 内置 Redis 的密码要与连接串一致。共享 Redis 的节点应指向同一实例和逻辑库 |
| 内置数据库和 Redis 的密码 | 首次正式部署时替换 Compose 中的示例密码,并同步修改 `SQL_DSN` 和 `REDIS_CONN_STRING`。已有数据库要先在数据库中更新账号密码,再同步连接配置。改 `POSTGRES_PASSWORD` 或 `MYSQL_ROOT_PASSWORD` 环境变量不会替已初始化的数据库改密码 |
| `SESSION_COOKIE_SECURE`、`SESSION_COOKIE_TRUSTED_URL` | 公网 HTTPS 控制台使用 `true`,并填实际浏览器访问的精确 HTTPS Origin,多个地址用英文逗号分隔。本地 HTTP 用 `false`,可信源留空。开发模板默认使用本地 HTTP |
| `TRUSTED_PROXIES` | 按实际网络填写可信反向代理 IP/CIDR,直连可设 `none`。迁移后代理地址变化时更新 |
| `NODE_TYPE`、`NODE_NAME` | 单节点用 `master`。多节点保留一个 `master` 负责迁移与主节点任务,其余设置 `slave`。`NODE_NAME` 为审计名称,每个节点使用独立且稳定的名称 |
正式模板从 `.env` 注入会话 HTTPS、可信代理和节点相关变量。数据库与 Redis 连接则按模板现有写法在对应服务的配置及应用 `environment` 中同步设置。更改环境变量后需重建应用容器。升级前备份数据库和持久化挂载,先停止旧版钱包及支付写入实例。支付网关的商户配置和站点「服务器地址」在管理后台保存,迁移时随数据库恢复;域名变更后更新站点地址和反向代理配置。
#### Docker 部署支付宝 AI付
1. **使用包含统一支付凭据功能的 NovaLink 镜像。** 在源码根目录执行 `docker build -t novalink-new-api:local .`。将 [docker-compose.yml](./docker-compose.yml) 中 `services.new-api.image` 的上游镜像 `calciumion/new-api:latest` 改为该镜像。也可以填写同版本的自有镜像名。
2. **在 Compose 文件同目录的 `.env` 配置密钥。** 首次生成统一支付密钥时运行 `openssl rand -base64 32`,把完整输出填到 `PAYMENT_CREDENTIAL_KEY=` 后,保留末尾的 `=`。已经使用统一密钥的部署沿用原值。站点没有支付凭据或历史支付凭据时可以留空。已有 v1.11.0 支付配置的部署按下方步骤迁移。
3. **确认 Compose 将变量传给容器。** 仓库的正式和开发 Compose 模板都已配置映射。如果使用自建 Compose 文件,在 `services.new-api.environment` **现有列表内**加上这一行,不要新建第二个 `environment`。宿主机 `.env` 只提供 Compose 的变量替换,缺少映射时不会自动传进容器。
```yaml
- "PAYMENT_CREDENTIAL_KEY=${PAYMENT_CREDENTIAL_KEY:-}"
```
4. **应用配置。** 在部署目录执行 `docker compose --env-file .env config -q` 检查配置。从旧版升级时先备份数据库,停止仍在处理付款和钱包写入的旧版实例。首次启动执行 `docker compose --env-file .env up -d`;数据库和 Redis 已运行、只需更新应用容器时执行 `docker compose --env-file .env up -d --no-deps --force-recreate new-api`。单独执行 `docker compose restart new-api` 不会重新读取环境变量。不需要删除数据库卷。
5. **在管理后台配置并验证。** 打开「系统设置 → 计费与支付 → 支付网关 → 支付宝(AI付)」,确认未再提示缺少密钥,然后添加商户。正式收款需确认支付合规,将站点的「服务器地址」设置为公网 HTTPS 地址,让反向代理把 `/api/alipay-direct/notify` 转发到应用,并配置已开通对应产品的生产商户后再开启网关。站内二维码需要当面付权限;不支持时可跳转到支付宝收银台。沙箱可用 [docker-compose.dev.yml](./docker-compose.dev.yml) 进行本地测试,无公网 HTTPS 时可通过查单确认,不会增加正式钱包余额或套餐权益。
**升级和迁移**
- 所有共用数据库的节点使用同一个持久的 `PAYMENT_CREDENTIAL_KEY`。密钥与数据库分别备份。
- 升级已有部署时先停止旧实例,备份数据库,并配置 `PAYMENT_CREDENTIAL_KEY`。主节点启动时会加密旧版网关保存的支付凭据,主节点启动成功后再启动从节点。
- 升级后,易支付、Stripe、Creem、Waffo 和 Waffo Pancake 默认暂停接新单。新订单绑定创建时的凭据版本。旧版订单沿用升级时保留的可用验证配置,旧版从未记录的更早凭据版本无法恢复。在后台核对配置并显式启用需要的网关。修改收款配置会再次暂停接新单。
订单超过「自动查单延迟」仍待支付时,后台会向支付宝查询,默认延迟 5 分钟。管理员也可在「支付宝订单」按站内订单号或支付宝交易号主动查单。用尚未同步的支付宝交易号查询时,需选中该笔交易的商户。订单列表显示首次确认支付的来源(验签回调或验签查单)。
---
@@ -326,7 +377,7 @@ git clone https://github.com/QuantumNous/new-api.git
cd new-api
```
Before starting, edit `docker-compose.yml`: replace the database and Redis example passwords in both the services and connection strings, and set a persistent random `SESSION_SECRET` (generate one with `openssl rand -hex 32`). For an HTTPS console, configure `SESSION_COOKIE_SECURE=true` and `SESSION_COOKIE_TRUSTED_URL` with its exact public HTTPS origin.
Before starting, edit the Compose file to replace the database and Redis example passwords in both the service settings and the connection strings. Set a persistent `SESSION_SECRET` in `.env` using a value generated by `openssl rand -hex 32`. For an HTTPS console, set `SESSION_COOKIE_SECURE=true` and set `SESSION_COOKIE_TRUSTED_URL` to the exact public HTTPS origin in the same `.env`. The repository's Compose template passes these values to the application container.
```bash
docker compose up -d
+9
View File
@@ -62,6 +62,15 @@ func IsRequestBodyTooLargeError(err error) bool {
return errors.As(err, &mbe)
}
// NormalizeRelayPath maps Playground relay paths (/pg/...) onto their canonical
// API path (/v1/...) for route matching while leaving other paths unchanged.
func NormalizeRelayPath(path string) string {
if rest, ok := strings.CutPrefix(path, "/pg/"); ok {
return "/v1/" + rest
}
return path
}
func GetRequestBody(c *gin.Context) (io.Seeker, error) {
// 首先检查是否有 BodyStorage 缓存
if storage, exists := c.Get(KeyBodyStorage); exists && storage != nil {
+1
View File
@@ -743,6 +743,7 @@
"stream scanner data: %s": "收到流数据: %s",
"streaming timeout seconds: %d": "流式超时: %d 秒",
"stripe topup": "Stripe 充值",
"subscription %d exhausted at settlement, %d quota of the final delta uncovered": "订阅 %d 在结算时已用尽,最终差额中有 %d 额度未扣除",
"subscription balance purchase": "余额购买订阅",
"subscription expiration": "订阅到期",
"subscription expire task failed: %v": "处理过期订阅失败: %v",
+2 -2
View File
@@ -36,7 +36,7 @@ type alipayDirectPayRequest struct {
}
func alipayDirectAvailability() (bool, int64) {
if !isPaymentComplianceConfirmed() || model.DB == nil || !model.AlipayDirectKeyConfigured() {
if !isPaymentComplianceConfirmed() || model.DB == nil || !model.PaymentCredentialKeyConfigured() {
return false, 0
}
settings, err := model.GetAlipayDirectSettings()
@@ -176,7 +176,7 @@ func StartAlipayDirect(c *gin.Context) {
return
}
order, err = model.ReserveAlipayDirectOrder(quote)
if errors.Is(err, model.ErrAlipayDirectUnavailable) || errors.Is(err, model.ErrAlipayDirectKey) || errors.Is(err, model.ErrTopUpQuotaLimitExceeded) {
if errors.Is(err, model.ErrAlipayDirectUnavailable) || errors.Is(err, model.ErrPaymentCredentialKey) || errors.Is(err, model.ErrTopUpQuotaLimitExceeded) {
common.ApiErrorStatus(c, http.StatusOK, err, gin.H{"order_created": false})
return
}
+1 -1
View File
@@ -41,7 +41,7 @@ func GetAlipayDirectAdmin(c *gin.Context) {
return
}
common.ApiSuccess(c, gin.H{"enabled": settings.Enabled, "price": settings.Price, "min_topup": settings.MinTopUp,
"query_delay_minutes": settings.EffectiveQueryDelayMinutes(), "key_configured": model.AlipayDirectKeyConfigured(), "merchants": merchants})
"query_delay_minutes": settings.EffectiveQueryDelayMinutes(), "key_configured": model.PaymentCredentialKeyConfigured(), "merchants": merchants})
}
func UpdateAlipayDirectAdmin(c *gin.Context) {
+1 -1
View File
@@ -72,7 +72,7 @@ func StartAlipayDirectReconciliation() {
ticker := time.NewTicker(20 * time.Second)
defer ticker.Stop()
for range ticker.C {
if !model.AlipayDirectKeyConfigured() {
if !model.PaymentCredentialKeyConfigured() {
continue
}
now := time.Now()
+5 -1
View File
@@ -90,7 +90,7 @@ func GetOptions(c *gin.Context) {
continue
}
value := common.Interface2String(v)
isSensitiveKey := strings.HasSuffix(k, "Token") ||
isSensitiveKey := model.IsPaymentCredentialOption(k) || model.PaymentGatewayStateOption(k) || strings.HasSuffix(k, "Token") ||
strings.HasSuffix(k, "Secret") ||
strings.HasSuffix(k, "Key") ||
strings.HasSuffix(k, "secret") ||
@@ -191,6 +191,10 @@ func UpdateOption(c *gin.Context) {
common.ApiErrorStatus(c, http.StatusBadRequest, common.NewMessage("Invalid parameters"))
return
}
if model.PaymentGatewayStateOption(option.Key) {
common.ApiErrorT(c, "Invalid parameters")
return
}
switch option.Value.(type) {
case bool:
option.Value = common.Interface2String(option.Value.(bool))
+224
View File
@@ -0,0 +1,224 @@
package controller
import (
"context"
"errors"
"net/http"
"strings"
"time"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/service"
"github.com/gin-gonic/gin"
"github.com/stripe/stripe-go/v81"
"github.com/stripe/stripe-go/v81/price"
"github.com/waffo-com/waffo-go/types/merchant"
pancake "github.com/waffo-com/waffo-pancake-sdk-go"
)
var paymentGatewayProviders = []string{model.PaymentProviderEpay, model.PaymentProviderStripe, model.PaymentProviderCreem, model.PaymentProviderWaffo, model.PaymentProviderWaffoPancake}
var errGatewayValidation = common.NewMessage("Payment gateway validation failed")
func paymentGatewayConfigured(provider string, config map[string]string, subscription bool) bool {
switch provider {
case model.PaymentProviderEpay:
return epayClientForConfig(config) != nil && len(epayConfiguredMethods(config["PayMethods"])) != 0
case model.PaymentProviderStripe:
key := config["StripeApiSecret"]
return (strings.HasPrefix(key, "sk_live_") || strings.HasPrefix(key, "rk_live_")) && config["StripeWebhookSecret"] != "" && (subscription || config["StripePriceId"] != "")
case model.PaymentProviderCreem:
products := strings.TrimSpace(config["CreemProducts"])
return config["CreemApiKey"] != "" && config["CreemWebhookSecret"] != "" && config["CreemTestMode"] != "true" && (subscription || products != "" && products != "[]")
case model.PaymentProviderWaffo:
return config["WaffoSandbox"] != "true" && config["WaffoMerchantId"] != "" && config["WaffoApiKey"] != "" && config["WaffoPrivateKey"] != "" && config["WaffoPublicCert"] != ""
case model.PaymentProviderWaffoPancake:
return config["WaffoPancakeStoreID"] != "" && config["WaffoPancakeMerchantID"] != "" && config["WaffoPancakePrivateKey"] != "" && (subscription || config["WaffoPancakeProductID"] != "")
default:
return false
}
}
func activePaymentGateway(provider string, subscription bool) model.PaymentGatewayConfiguration {
if !isPaymentComplianceConfirmed() {
return model.PaymentGatewayConfiguration{}
}
config, err := model.PaymentGatewayActiveConfiguration(provider)
if err != nil || !paymentGatewayConfigured(provider, config.Values, subscription) {
return model.PaymentGatewayConfiguration{}
}
return config
}
const checkoutGatewayKey = "checkout_gateway_configuration"
func RequirePaymentGateway(provider string, subscription bool) gin.HandlerFunc {
return func(c *gin.Context) {
config := activePaymentGateway(provider, subscription)
if config.RevisionID <= 0 {
paymentError(c, model.ErrPaymentGatewayUnavailable)
c.Abort()
return
}
c.Set(checkoutGatewayKey, config)
c.Next()
}
}
func checkoutGateway(c *gin.Context) model.PaymentGatewayConfiguration {
config, _ := c.Get(checkoutGatewayKey)
value, _ := config.(model.PaymentGatewayConfiguration)
return value
}
func GetPaymentGateways(c *gin.Context) {
data := make(map[string]gin.H, len(paymentGatewayProviders))
for _, provider := range paymentGatewayProviders {
draft, err := model.PaymentGatewayDraft(provider)
if err != nil {
common.ApiError(c, err)
return
}
config, _ := model.PaymentGatewayActiveConfiguration(provider)
data[provider] = gin.H{"configured": paymentGatewayConfigured(provider, draft, true), "enabled": config.RevisionID > 0}
}
common.ApiSuccess(c, data)
}
func UpdatePaymentGateway(c *gin.Context) {
provider := c.Param("gateway")
var input struct {
Enabled *bool `json:"enabled"`
}
if c.ShouldBindJSON(&input) != nil || input.Enabled == nil {
common.ApiErrorT(c, "Invalid parameters")
return
}
var err error
if *input.Enabled {
if !requirePaymentCompliance(c) {
return
}
ctx, cancel := context.WithTimeout(c.Request.Context(), 12*time.Second)
defer cancel()
err = model.ActivatePaymentGateway(provider, func(draft map[string]string) error {
if !paymentGatewayConfigured(provider, draft, true) {
return common.NewMessage("Payment gateway configuration is incomplete")
}
return validatePaymentGateway(ctx, provider, draft)
})
} else {
err = model.SetPaymentGatewayConfiguration(provider, nil)
}
if err != nil {
common.ApiError(c, err)
return
}
recordPaymentGatewayChange(c, provider, "payment_gateway_availability_changed", model.AuditFields{"enabled": *input.Enabled})
common.ApiSuccess(c, nil)
}
func validatePaymentGateway(ctx context.Context, provider string, draft map[string]string) error {
switch provider {
case model.PaymentProviderStripe:
client := price.Client{B: stripe.GetBackend(stripe.APIBackend), Key: draft["StripeApiSecret"]}
if priceID := draft["StripePriceId"]; priceID != "" {
result, err := client.Get(priceID, &stripe.PriceParams{Params: stripe.Params{Context: ctx}})
if err != nil || result == nil || !result.Active || !result.Livemode {
return errGatewayValidation
}
} else {
params := &stripe.PriceListParams{Active: stripe.Bool(true)}
params.Context, params.Limit = ctx, stripe.Int64(1)
if iter := client.List(params); !iter.Next() {
return errGatewayValidation
}
}
case model.PaymentProviderCreem:
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.creem.io/v1/products/search?page_size=1", nil)
if err != nil {
return errGatewayValidation
}
req.Header.Set("x-api-key", draft["CreemApiKey"])
client := http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
resp, err := client.Do(req)
if err != nil {
return errGatewayValidation
}
_ = resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return errGatewayValidation
}
case model.PaymentProviderWaffoPancake:
catalog, err := service.ListWaffoPancakeCatalog(ctx, draft["WaffoPancakeMerchantID"], draft["WaffoPancakePrivateKey"])
if err != nil {
return errGatewayValidation
}
for _, store := range catalog.Stores {
if store.ID != draft["WaffoPancakeStoreID"] || !store.ProdEnabled || !strings.EqualFold(store.Status, "active") {
continue
}
if draft["WaffoPancakeProductID"] == "" {
return nil
}
for _, product := range store.OnetimeProducts {
if product.ID == draft["WaffoPancakeProductID"] {
return nil
}
}
}
return errGatewayValidation
case model.PaymentProviderWaffo:
sdk, err := waffoSDKForConfig(draft)
if err != nil {
return errGatewayValidation
}
result, err := sdk.MerchantConfig().Inquiry(ctx, &merchant.InquiryMerchantConfigParams{MerchantID: draft["WaffoMerchantId"]}, nil)
if err != nil || result == nil || !result.IsSuccess() || result.Data == nil || (result.Data.MerchantID != "" && result.Data.MerchantID != draft["WaffoMerchantId"]) {
return errGatewayValidation
}
}
return nil
}
func ClearPaymentGateway(c *gin.Context) {
provider := c.Param("gateway")
if err := model.ClearPaymentGatewayConfig(provider); err != nil {
common.ApiError(c, err)
return
}
recordPaymentGatewayChange(c, provider, "payment_gateway_configuration_cleared", nil)
common.ApiSuccess(c, nil)
}
func recordPaymentGatewayChange(c *gin.Context, provider, action string, params model.AuditFields) {
if params == nil {
params = model.AuditFields{}
}
params["provider"] = provider
model.RecordAuditLog(c, model.AuditLog{UserId: c.GetInt("id"), ActorRole: c.GetInt("role"), Category: model.AuditCategoryOperation,
Action: action, Success: true, Other: model.AuditOther{Op: &model.AuditOperation{Action: action, Params: params}},
})
}
func paymentGatewayOrderError(c *gin.Context, err error) {
if errors.Is(err, model.ErrPaymentGatewayUnavailable) {
paymentError(c, model.ErrPaymentGatewayUnavailable)
return
}
paymentError(c, common.NewMessage("Failed to create order"))
}
func stopRejectedPaymentGateway(provider string, id int, err error) {
if err == nil {
return
}
var stripeError *stripe.Error
var pancakeError *pancake.Error
if (provider == model.PaymentProviderStripe && errors.As(err, &stripeError) && (stripeError.HTTPStatusCode == http.StatusUnauthorized || stripeError.Code == stripe.ErrorCodeAccountInvalid)) ||
(provider == model.PaymentProviderWaffoPancake && errors.As(err, &pancakeError) && pancakeError.Status == http.StatusUnauthorized) {
if stopErr := model.StopPaymentGatewayRevision(provider, id); stopErr != nil {
common.SysError("Failed to stop a rejected payment gateway")
}
}
}
+14 -109
View File
@@ -5,9 +5,9 @@ import (
"strconv"
"strings"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/setting"
"github.com/QuantumNous/new-api/setting/operation_setting"
)
@@ -15,114 +15,19 @@ func isPaymentComplianceConfirmed() bool {
return operation_setting.IsPaymentComplianceConfirmed()
}
func isStripeTopUpEnabled() bool {
if !isPaymentComplianceConfirmed() {
return false
}
return strings.TrimSpace(setting.StripeApiSecret) != "" &&
strings.TrimSpace(setting.StripeWebhookSecret) != "" &&
strings.TrimSpace(setting.StripePriceId) != ""
}
func isStripeWebhookConfigured() bool {
return strings.TrimSpace(setting.StripeWebhookSecret) != ""
}
func isStripeWebhookEnabled() bool {
return isStripeTopUpEnabled()
}
func isCreemTopUpEnabled() bool {
if !isPaymentComplianceConfirmed() {
return false
}
products := strings.TrimSpace(setting.CreemProducts)
return strings.TrimSpace(setting.CreemApiKey) != "" &&
products != "" &&
products != "[]"
}
func isCreemWebhookConfigured() bool {
return strings.TrimSpace(setting.CreemWebhookSecret) != ""
}
func isCreemWebhookEnabled() bool {
return isCreemTopUpEnabled() && isCreemWebhookConfigured()
}
func isWaffoTopUpEnabled() bool {
if !isPaymentComplianceConfirmed() {
return false
}
if !setting.WaffoEnabled {
return false
}
return isWaffoWebhookConfigured()
}
func isWaffoWebhookConfigured() bool {
if setting.WaffoSandbox {
return strings.TrimSpace(setting.WaffoSandboxApiKey) != "" &&
strings.TrimSpace(setting.WaffoSandboxPrivateKey) != "" &&
strings.TrimSpace(setting.WaffoSandboxPublicCert) != ""
}
return strings.TrimSpace(setting.WaffoApiKey) != "" &&
strings.TrimSpace(setting.WaffoPrivateKey) != "" &&
strings.TrimSpace(setting.WaffoPublicCert) != ""
}
func isWaffoWebhookEnabled() bool {
return isWaffoTopUpEnabled()
}
func isWaffoPancakeTopUpEnabled() bool {
if !isPaymentComplianceConfirmed() {
return false
}
// Presence-of-credentials = enabled. Webhook public keys ship inside
// the SDK; mode (test/prod) is read from each event.
return strings.TrimSpace(setting.WaffoPancakeMerchantID) != "" &&
strings.TrimSpace(setting.WaffoPancakePrivateKey) != "" &&
strings.TrimSpace(setting.WaffoPancakeProductID) != ""
}
func isWaffoPancakeWebhookConfigured() bool {
return isWaffoPancakeTopUpEnabled()
}
func isWaffoPancakeWebhookEnabled() bool {
return isWaffoPancakeTopUpEnabled()
}
func isEpayTopUpEnabled() bool {
if !isPaymentComplianceConfirmed() {
return false
}
return isEpayWebhookConfigured() && len(epayPaymentMethods()) > 0
}
func isEpayWebhookConfigured() bool {
if strings.TrimSpace(operation_setting.PayAddress) == "" || strings.TrimSpace(operation_setting.EpayId) == "" {
return false
}
if paymentSetting := operation_setting.GetPaymentSetting(); paymentSetting.EpaySignType == operation_setting.EpaySignTypeRSA {
return strings.TrimSpace(paymentSetting.EpayMerchantPrivateKey) != "" &&
strings.TrimSpace(paymentSetting.EpayPlatformPublicKey) != ""
}
return strings.TrimSpace(operation_setting.EpayKey) != ""
}
func isEpayWebhookEnabled() bool {
return isPaymentComplianceConfirmed() && isEpayWebhookConfigured()
}
// A gateway identifier belongs to its own checkout, never to Epay's type parameter.
func epayPaymentMethods() []map[string]string {
methods := make([]map[string]string, 0, len(operation_setting.PayMethods))
func epayConfiguredMethods(raw string) []map[string]string {
var configured []map[string]string
if common.UnmarshalJsonStr(raw, &configured) != nil {
return []map[string]string{}
}
return filterEpayMethods(configured)
}
func filterEpayMethods(configured []map[string]string) []map[string]string {
methods := make([]map[string]string, 0, len(configured))
seen := make(map[string]bool)
for _, method := range operation_setting.PayMethods {
for _, method := range configured {
kind := method["type"]
switch kind {
case "", model.PaymentMethodStripe, model.PaymentMethodCreem, model.PaymentMethodWaffo,
@@ -138,8 +43,8 @@ func epayPaymentMethods() []map[string]string {
return methods
}
func epayPaymentMethod(kind string) (map[string]string, bool) {
for _, method := range epayPaymentMethods() {
func findEpayMethod(methods []map[string]string, kind string) (map[string]string, bool) {
for _, method := range methods {
if method["type"] == kind {
return method, true
}
+160 -290
View File
@@ -43,194 +43,78 @@ func confirmPaymentComplianceForTest(t *testing.T) {
paymentSetting.ComplianceTermsVersion = operation_setting.CurrentComplianceTermsVersion
}
func TestStripeWebhookEnabledRequiresTopUpAndWebhookConfig(t *testing.T) {
confirmPaymentComplianceForTest(t)
originalAPISecret := setting.StripeApiSecret
originalWebhookSecret := setting.StripeWebhookSecret
originalPriceID := setting.StripePriceId
func setupPaymentWebhookDB(t *testing.T, models ...any) *gorm.DB {
t.Helper()
t.Setenv("LOG_SQL_DSN", "")
t.Setenv("PAYMENT_CREDENTIAL_KEY", base64.StdEncoding.EncodeToString([]byte(strings.Repeat("p", 32))))
oldDB, oldLogDB := model.DB, model.LOG_DB
oldMainType, oldLogType := common.MainDatabaseType(), common.LogDatabaseType()
oldRedis, oldBatch, oldQuota := common.RedisEnabled, common.BatchUpdateEnabled, common.QuotaPerUnit
oldOptions, oldMaster := common.OptionMap, common.IsMasterNode
db, err := gorm.Open(sqlite.Open("file:"+url.QueryEscape(t.Name())+"?mode=memory&cache=shared"), &gorm.Config{})
require.NoError(t, err)
connection, err := db.DB()
require.NoError(t, err)
// Subscription completion reads the plan and DB timestamp outside its transaction.
connection.SetMaxOpenConns(4)
model.DB, model.LOG_DB = db, db
common.SetDatabaseTypes(common.DatabaseTypeSQLite, common.DatabaseTypeSQLite)
common.RedisEnabled, common.BatchUpdateEnabled, common.QuotaPerUnit = false, false, 500_000
common.OptionMap = make(map[string]string)
common.IsMasterNode = false
t.Cleanup(func() {
setting.StripeApiSecret = originalAPISecret
setting.StripeWebhookSecret = originalWebhookSecret
setting.StripePriceId = originalPriceID
model.DB, model.LOG_DB = oldDB, oldLogDB
common.SetDatabaseTypes(oldMainType, oldLogType)
common.RedisEnabled, common.BatchUpdateEnabled, common.QuotaPerUnit = oldRedis, oldBatch, oldQuota
common.OptionMap, common.IsMasterNode = oldOptions, oldMaster
assert.NoError(t, connection.Close())
})
setting.StripeWebhookSecret = ""
setting.StripeApiSecret = "sk_test_123"
setting.StripePriceId = "price_123"
require.False(t, isStripeWebhookEnabled())
setting.StripeWebhookSecret = "whsec_test"
require.True(t, isStripeWebhookEnabled())
setting.StripePriceId = ""
require.False(t, isStripeWebhookEnabled())
require.NoError(t, model.InitLogDB())
common.IsMasterNode = oldMaster
require.NoError(t, db.AutoMigrate(append(model.PaymentGatewayPersistenceModels(), models...)...))
return db
}
func TestCreemWebhookEnabledRequiresTopUpAndWebhookConfig(t *testing.T) {
confirmPaymentComplianceForTest(t)
originalAPIKey := setting.CreemApiKey
originalProducts := setting.CreemProducts
originalWebhookSecret := setting.CreemWebhookSecret
t.Cleanup(func() {
setting.CreemApiKey = originalAPIKey
setting.CreemProducts = originalProducts
setting.CreemWebhookSecret = originalWebhookSecret
})
setting.CreemWebhookSecret = ""
setting.CreemApiKey = "creem_api_key"
setting.CreemProducts = `[{"productId":"prod_123"}]`
require.False(t, isCreemWebhookEnabled())
setting.CreemWebhookSecret = "creem_secret"
require.True(t, isCreemWebhookEnabled())
setting.CreemProducts = "[]"
require.False(t, isCreemWebhookEnabled())
}
func TestWaffoWebhookEnabledRequiresTopUpAndWebhookConfig(t *testing.T) {
confirmPaymentComplianceForTest(t)
originalEnabled := setting.WaffoEnabled
originalSandbox := setting.WaffoSandbox
originalAPIKey := setting.WaffoApiKey
originalPrivateKey := setting.WaffoPrivateKey
originalPublicCert := setting.WaffoPublicCert
originalSandboxAPIKey := setting.WaffoSandboxApiKey
originalSandboxPrivateKey := setting.WaffoSandboxPrivateKey
originalSandboxPublicCert := setting.WaffoSandboxPublicCert
t.Cleanup(func() {
setting.WaffoEnabled = originalEnabled
setting.WaffoSandbox = originalSandbox
setting.WaffoApiKey = originalAPIKey
setting.WaffoPrivateKey = originalPrivateKey
setting.WaffoPublicCert = originalPublicCert
setting.WaffoSandboxApiKey = originalSandboxAPIKey
setting.WaffoSandboxPrivateKey = originalSandboxPrivateKey
setting.WaffoSandboxPublicCert = originalSandboxPublicCert
})
setting.WaffoEnabled = true
setting.WaffoSandbox = false
setting.WaffoApiKey = ""
setting.WaffoPrivateKey = "private"
setting.WaffoPublicCert = "public"
require.False(t, isWaffoWebhookEnabled())
setting.WaffoApiKey = "api"
require.True(t, isWaffoWebhookEnabled())
setting.WaffoEnabled = false
require.False(t, isWaffoWebhookEnabled())
setting.WaffoEnabled = true
setting.WaffoSandbox = true
setting.WaffoSandboxApiKey = ""
setting.WaffoSandboxPrivateKey = "sandbox_private"
setting.WaffoSandboxPublicCert = "sandbox_public"
require.False(t, isWaffoWebhookEnabled())
setting.WaffoSandboxApiKey = "sandbox_api"
require.True(t, isWaffoWebhookEnabled())
}
func TestWaffoPancakeWebhookEnabledRequiresTopUpAndWebhookConfig(t *testing.T) {
confirmPaymentComplianceForTest(t)
originalMerchantID := setting.WaffoPancakeMerchantID
originalPrivateKey := setting.WaffoPancakePrivateKey
originalProductID := setting.WaffoPancakeProductID
t.Cleanup(func() {
setting.WaffoPancakeMerchantID = originalMerchantID
setting.WaffoPancakePrivateKey = originalPrivateKey
setting.WaffoPancakeProductID = originalProductID
})
// Presence of all three credentials enables the gateway. Webhook public
// keys are bundled in the SDK and there is no separate Enabled toggle —
// clear any of the three fields to disable.
setting.WaffoPancakeMerchantID = ""
setting.WaffoPancakePrivateKey = "private"
setting.WaffoPancakeProductID = "product"
require.False(t, isWaffoPancakeWebhookEnabled())
setting.WaffoPancakeMerchantID = "merchant"
require.True(t, isWaffoPancakeWebhookEnabled())
setting.WaffoPancakeProductID = ""
require.False(t, isWaffoPancakeWebhookEnabled())
setting.WaffoPancakeProductID = "product"
setting.WaffoPancakePrivateKey = ""
require.False(t, isWaffoPancakeWebhookEnabled())
}
func TestEpayWebhookRemainsEnabledWhenMerchantStopsNewOrders(t *testing.T) {
confirmPaymentComplianceForTest(t)
originalPayAddress := operation_setting.PayAddress
originalEpayID := operation_setting.EpayId
originalEpayKey := operation_setting.EpayKey
paymentSetting := operation_setting.GetPaymentSetting()
originalSignType := paymentSetting.EpaySignType
originalMerchantPrivateKey := paymentSetting.EpayMerchantPrivateKey
originalPlatformPublicKey := paymentSetting.EpayPlatformPublicKey
originalPayMethods := operation_setting.PayMethods
t.Cleanup(func() {
operation_setting.PayAddress = originalPayAddress
operation_setting.EpayId = originalEpayID
operation_setting.EpayKey = originalEpayKey
paymentSetting.EpaySignType = originalSignType
paymentSetting.EpayMerchantPrivateKey = originalMerchantPrivateKey
paymentSetting.EpayPlatformPublicKey = originalPlatformPublicKey
operation_setting.PayMethods = originalPayMethods
})
operation_setting.PayAddress = "https://pay.example.com"
operation_setting.EpayId = "epay_id"
operation_setting.EpayKey = ""
paymentSetting.EpaySignType = operation_setting.EpaySignTypeMD5
operation_setting.PayMethods = []map[string]string{{"type": "alipay"}}
require.False(t, isEpayWebhookEnabled())
operation_setting.EpayKey = "epay_key"
require.True(t, isEpayWebhookEnabled())
operation_setting.PayMethods = nil
require.False(t, isEpayTopUpEnabled())
require.True(t, isEpayWebhookEnabled())
operation_setting.PayMethods = []map[string]string{{"type": "stripe"}, {"type": "alipay_direct"}}
require.False(t, isEpayTopUpEnabled())
require.True(t, isEpayWebhookEnabled())
// RSA needs both keys, and the MD5 key no longer counts.
operation_setting.PayMethods = []map[string]string{{"type": "alipay"}}
paymentSetting.EpaySignType = operation_setting.EpaySignTypeRSA
paymentSetting.EpayMerchantPrivateKey = "merchant_private_key"
paymentSetting.EpayPlatformPublicKey = ""
require.False(t, isEpayWebhookEnabled())
paymentSetting.EpayPlatformPublicKey = "platform_public_key"
operation_setting.EpayKey = ""
require.True(t, isEpayWebhookEnabled())
// stoppedWebhookRevision creates the immutable checkout configuration and stops
// new payments before callbacks arrive; notification handling must still work.
func stoppedWebhookRevision(t *testing.T, provider string) model.PaymentGatewayConfiguration {
t.Helper()
draft, err := model.PaymentGatewayDraft(provider)
require.NoError(t, err)
require.NoError(t, model.SetPaymentGatewayConfiguration(provider, draft))
active, err := model.PaymentGatewayActiveConfiguration(provider)
require.NoError(t, err)
require.Positive(t, active.RevisionID)
require.NoError(t, model.SetPaymentGatewayConfiguration(provider, nil))
return active
}
func TestEpayChannelListRequiresMerchantConfiguration(t *testing.T) {
confirmPaymentComplianceForTest(t)
setupEpayCallbackTest(t)
originalStripeAPI, originalStripeWebhook, originalStripePrice := setting.StripeApiSecret, setting.StripeWebhookSecret, setting.StripePriceId
t.Cleanup(func() {
setting.StripeApiSecret, setting.StripeWebhookSecret, setting.StripePriceId = originalStripeAPI, originalStripeWebhook, originalStripePrice
})
setting.StripeApiSecret, setting.StripeWebhookSecret, setting.StripePriceId = "fixture", "fixture", "fixture"
operation_setting.GetPaymentSetting().EpaySignType = operation_setting.EpaySignTypeMD5
operation_setting.PayMethods = []map[string]string{
{"type": "alipay", "name": "Alipay"},
{"type": "stripe", "name": "Credit card"},
}
for _, configured := range []bool{false, true} {
t.Run(fmt.Sprintf("configured=%t", configured), func(t *testing.T) {
operation_setting.EpayKey = ""
if configured {
operation_setting.EpayKey = "fixture"
require.NoError(t, model.UpdateOptionsBulk(map[string]string{
"PayAddress": "https://pay.example.com", "EpayId": "epay_id", "EpayKey": "test-key",
"PayMethods": `[{"type":"alipay","name":"Alipay"},{"type":"stripe","name":"Credit card"}]`,
"StripeApiSecret": "sk_live_fixture", "StripeWebhookSecret": "whsec_fixture", "StripePriceId": "price_fixture",
}))
stripe, err := model.PaymentGatewayDraft(model.PaymentProviderStripe)
require.NoError(t, err)
require.NoError(t, model.SetPaymentGatewayConfiguration(model.PaymentProviderStripe, stripe))
for _, state := range []string{"saved", "enabled", "channels removed"} {
t.Run(state, func(t *testing.T) {
if state != "saved" {
draft, err := model.PaymentGatewayDraft(model.PaymentProviderEpay)
require.NoError(t, err)
require.NoError(t, model.SetPaymentGatewayConfiguration(model.PaymentProviderEpay, draft))
}
if state == "channels removed" {
require.NoError(t, model.UpdateOption("PayMethods", `[{"type":"stripe","name":"Credit card"}]`))
}
configured := state == "enabled"
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
c.Request = httptest.NewRequest(http.MethodGet, "/api/user/topup/info", nil)
@@ -265,38 +149,33 @@ type epayCallbackCase struct {
validPending bool
}
// setupEpayCallbackTest configures an Epay gateway and leaves model.DB nil:
// rejected callbacks and valid non-success events must never reach settlement,
// so an accidental attempt to settle fails the test.
func setupEpayCallbackTest(t *testing.T) {
func setupEpayCallbackTest(t *testing.T) *gorm.DB {
t.Helper()
confirmPaymentComplianceForTest(t)
originalPayAddress := operation_setting.PayAddress
originalEpayID := operation_setting.EpayId
originalEpayKey := operation_setting.EpayKey
oldPayAddress, oldEpayID, oldEpayKey := operation_setting.PayAddress, operation_setting.EpayId, operation_setting.EpayKey
oldCallbackAddress, oldPayMethods := operation_setting.CustomCallbackAddress, operation_setting.PayMethods
paymentSetting := operation_setting.GetPaymentSetting()
originalSignType := paymentSetting.EpaySignType
originalMerchantPrivateKey := paymentSetting.EpayMerchantPrivateKey
originalPlatformPublicKey := paymentSetting.EpayPlatformPublicKey
originalPayMethods := operation_setting.PayMethods
originalServerAddress := system_setting.ServerAddress
originalDB := model.DB
oldPaymentSetting := *paymentSetting
oldServerAddress := system_setting.ServerAddress
t.Cleanup(func() {
operation_setting.PayAddress = originalPayAddress
operation_setting.EpayId = originalEpayID
operation_setting.EpayKey = originalEpayKey
paymentSetting.EpaySignType = originalSignType
paymentSetting.EpayMerchantPrivateKey = originalMerchantPrivateKey
paymentSetting.EpayPlatformPublicKey = originalPlatformPublicKey
operation_setting.PayMethods = originalPayMethods
system_setting.ServerAddress = originalServerAddress
model.DB = originalDB
operation_setting.PayAddress, operation_setting.EpayId, operation_setting.EpayKey = oldPayAddress, oldEpayID, oldEpayKey
operation_setting.CustomCallbackAddress, operation_setting.PayMethods = oldCallbackAddress, oldPayMethods
*paymentSetting = oldPaymentSetting
system_setting.ServerAddress = oldServerAddress
})
operation_setting.PayAddress = "https://pay.example.com"
operation_setting.EpayId = "epay_id"
operation_setting.PayMethods = []map[string]string{{"type": "alipay"}}
paymentSetting.EpaySignType = operation_setting.EpaySignTypeMD5
paymentSetting.EpayMerchantPrivateKey, paymentSetting.EpayPlatformPublicKey = "", ""
system_setting.ServerAddress = "https://dashboard.example.com"
model.DB = nil
return setupPaymentWebhookDB(t)
}
func insertEpayCallbackOrders(t *testing.T, revision int, tradeNumbers ...string) {
t.Helper()
for _, tradeNo := range tradeNumbers {
wallet := model.TopUp{TradeNo: tradeNo, PaymentProvider: model.PaymentProviderEpay, PaymentMethod: "alipay", Status: common.TopUpStatusPending, PaymentCredentialRevisionID: revision}
subscription := model.SubscriptionOrder{TradeNo: tradeNo, PaymentProvider: model.PaymentProviderEpay, PaymentMethod: "alipay", Status: common.TopUpStatusPending, PaymentCredentialRevisionID: revision}
require.NoError(t, model.DB.Create(&wallet).Error)
require.NoError(t, model.DB.Create(&subscription).Error)
}
}
// assertEpayCallbacksVerifyBeforeSettlement sends each callback to the top-up
@@ -378,10 +257,11 @@ func newEpayRSAKeyPairForTest(t *testing.T) (string, string) {
func TestEpayCallbacksVerifyBeforeSettlement(t *testing.T) {
setupEpayCallbackTest(t)
paymentSetting := operation_setting.GetPaymentSetting()
paymentSetting.EpaySignType = operation_setting.EpaySignTypeMD5
operation_setting.EpayKey = "test-key"
require.True(t, isEpayWebhookEnabled())
require.NoError(t, model.UpdateOptionsBulk(map[string]string{
"PayAddress": "https://pay.example.com", "EpayId": "epay_id", "EpayKey": "test-key",
}))
revision := stoppedWebhookRevision(t, model.PaymentProviderEpay)
insertEpayCallbackOrders(t, revision.RevisionID, "order", "other&out_trade_no=order")
// Both ambiguous maps below had this same valid signing string in v0.0.4.
// This must fail because of parameter ambiguity, not a mismatched signature.
@@ -418,17 +298,22 @@ func TestEpayCallbacksVerifyBeforeSettlement(t *testing.T) {
func TestEpayRSAModeSignsOrdersAndVerifiesCallbacks(t *testing.T) {
setupEpayCallbackTest(t)
paymentSetting := operation_setting.GetPaymentSetting()
merchantPrivateKey, merchantPublicKey := newEpayRSAKeyPairForTest(t)
platformPrivateKey, platformPublicKey := newEpayRSAKeyPairForTest(t)
paymentSetting.EpaySignType = operation_setting.EpaySignTypeRSA
// A leftover MD5 key must not be accepted once RSA is selected.
operation_setting.EpayKey = "test-key"
paymentSetting.EpayMerchantPrivateKey = merchantPrivateKey
paymentSetting.EpayPlatformPublicKey = platformPublicKey
require.True(t, isEpayWebhookEnabled())
// Keep an MD5 key in the draft to verify RSA callbacks cannot fall back to it.
require.NoError(t, model.UpdateOptionsBulk(map[string]string{
"PayAddress": "https://pay.example.com", "EpayId": "epay_id", "EpayKey": "test-key",
operation_setting.EpayMerchantPrivateKeyOptionKey: merchantPrivateKey,
operation_setting.EpayPlatformPublicKeyOptionKey: platformPublicKey,
}))
require.NoError(t, model.UpdateOption(operation_setting.EpaySignTypeOptionKey, operation_setting.EpaySignTypeRSA))
active := stoppedWebhookRevision(t, model.PaymentProviderEpay)
insertEpayCallbackOrders(t, active.RevisionID, "order")
require.NoError(t, model.UpdateOptionsBulk(map[string]string{
"EpayId": "rotated_epay_id", operation_setting.EpayPlatformPublicKeyOptionKey: merchantPublicKey,
}))
client := GetEpayClient()
client := epayClientForConfig(active.Values)
require.NotNil(t, client)
notifyURL, err := url.Parse("https://dashboard.example.com/api/user/epay/notify")
require.NoError(t, err)
@@ -505,28 +390,23 @@ func TestEpayRSAModeSignsOrdersAndVerifiesCallbacks(t *testing.T) {
func TestVerifiedPaymentWebhookReceipts(t *testing.T) {
confirmPaymentComplianceForTest(t)
oldDB, oldLogDB := model.DB, model.LOG_DB
oldType, oldRedis := common.MainDatabaseType(), common.RedisEnabled
oldStripeKey, oldStripePrice, oldStripeWebhook := setting.StripeApiSecret, setting.StripePriceId, setting.StripeWebhookSecret
oldCreemKey, oldCreemProducts, oldCreemWebhook := setting.CreemApiKey, setting.CreemProducts, setting.CreemWebhookSecret
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
require.NoError(t, err)
connection, err := db.DB()
require.NoError(t, err)
connection.SetMaxOpenConns(1)
model.DB, model.LOG_DB, common.RedisEnabled = db, db, false
common.SetMainDatabaseType(common.DatabaseTypeSQLite)
setting.StripeApiSecret, setting.StripePriceId, setting.StripeWebhookSecret = "sk_test_receipts", "price_receipts", "whsec_receipts"
setting.CreemApiKey, setting.CreemProducts, setting.CreemWebhookSecret = "creem_receipts", `[{"productId":"receipt-product"}]`, "creem_webhook_receipts"
t.Cleanup(func() {
model.DB, model.LOG_DB, common.RedisEnabled = oldDB, oldLogDB, oldRedis
common.SetMainDatabaseType(oldType)
setting.StripeApiSecret, setting.StripePriceId, setting.StripeWebhookSecret = oldStripeKey, oldStripePrice, oldStripeWebhook
setting.CreemApiKey, setting.CreemProducts, setting.CreemWebhookSecret = oldCreemKey, oldCreemProducts, oldCreemWebhook
assert.NoError(t, connection.Close())
})
models := append([]any{&model.User{}, &model.TopUp{}, &model.Redemption{}, &model.SubscriptionOrder{}, &model.Log{}, &model.PaymentReceipt{}}, model.UserOperationModels()...)
require.NoError(t, db.AutoMigrate(models...))
models := append([]any{&model.User{}, &model.Redemption{}, &model.Log{}, &model.PaymentReceipt{}}, model.UserOperationModels()...)
db := setupPaymentWebhookDB(t, models...)
const stripeSecret, creemSecret = "whsec_receipts", "creem_webhook_receipts"
require.NoError(t, model.UpdateOptionsBulk(map[string]string{
"StripeApiSecret": "sk_live_receipts", "StripePriceId": "price_receipts", "StripeWebhookSecret": stripeSecret,
"CreemApiKey": "creem_receipts", "CreemWebhookSecret": creemSecret,
}))
revisions := map[string]int{
model.PaymentProviderStripe: stoppedWebhookRevision(t, model.PaymentProviderStripe).RevisionID,
model.PaymentProviderCreem: stoppedWebhookRevision(t, model.PaymentProviderCreem).RevisionID,
}
require.NoError(t, db.Create(&model.UserAnnualLevelEpoch{ID: 1}).Error)
router := gin.New()
router.POST("/stripe", StripeWebhook)
@@ -550,16 +430,16 @@ func TestVerifiedPaymentWebhookReceipts(t *testing.T) {
if !tc.missingUser {
require.NoError(t, db.Create(&model.User{Id: userID, Username: tradeNo, AffCode: tradeNo, Status: common.UserStatusEnabled}).Error)
}
order := model.TopUp{UserId: userID, TradeNo: tradeNo, Amount: 100, Money: 2, PaymentProvider: tc.provider, PaymentMethod: tc.provider, Status: common.TopUpStatusPending}
order := model.TopUp{UserId: userID, TradeNo: tradeNo, Amount: 100, Money: 2, PaymentProvider: tc.provider, PaymentMethod: tc.provider, Status: common.TopUpStatusPending, PaymentCredentialRevisionID: revisions[tc.provider]}
require.NoError(t, db.Create(&order).Error)
var payload map[string]any
if tc.provider == model.PaymentProviderStripe {
object := map[string]any{"id": "cs_test_receipt", "object": "checkout.session", "client_reference_id": tradeNo, "status": "complete", "payment_status": "paid", "amount_total": 1234, "currency": tc.currency}
object := map[string]any{"id": "cs_live_receipt", "object": "checkout.session", "client_reference_id": tradeNo, "status": "complete", "payment_status": "paid", "amount_total": 1234, "currency": tc.currency}
eventType := "checkout.session.completed"
if tc.missingUser {
eventType = "checkout.session.async_payment_succeeded"
}
payload = map[string]any{"id": "evt_receipt", "object": "event", "type": eventType, "data": map[string]any{"object": object}}
payload = map[string]any{"id": "evt_receipt", "object": "event", "livemode": true, "type": eventType, "data": map[string]any{"object": object}}
} else {
paidOrder := map[string]any{"id": "creem-order", "status": "paid", "type": "onetime", "currency": tc.currency}
if !tc.missingAmount {
@@ -572,10 +452,10 @@ func TestVerifiedPaymentWebhookReceipts(t *testing.T) {
var header, signature string
if tc.provider == model.PaymentProviderStripe {
header = "Stripe-Signature"
signature = webhook.GenerateTestSignedPayload(&webhook.UnsignedPayload{Payload: body, Secret: setting.StripeWebhookSecret}).Header
signature = webhook.GenerateTestSignedPayload(&webhook.UnsignedPayload{Payload: body, Secret: stripeSecret}).Header
} else {
header = CreemSignatureHeader
signature = generateCreemSignature(string(body), setting.CreemWebhookSecret)
signature = generateCreemSignature(string(body), creemSecret)
}
if tc.tampered {
body = []byte(strings.Replace(string(body), "1234", "9999", 1))
@@ -663,7 +543,7 @@ func TestVerifiedPaymentWebhookReceipts(t *testing.T) {
// setupWaffoPaymentWebhookTest uses only throwaway RSA keys. Pancake v0.3.1
// resolves these environment variables before its bundled public keys, so tests
// exercise the real configured verifier without replacing any production code.
func setupWaffoPaymentWebhookTest(t *testing.T) (*gorm.DB, *gin.Engine, *waffoutils.KeyPair, *waffoutils.KeyPair) {
func setupWaffoPaymentWebhookTest(t *testing.T) (*gorm.DB, *gin.Engine, *waffoutils.KeyPair, *waffoutils.KeyPair, map[string]int) {
t.Helper()
confirmPaymentComplianceForTest(t)
platform, err := waffoutils.GenerateKeyPair()
@@ -673,45 +553,34 @@ func setupWaffoPaymentWebhookTest(t *testing.T) (*gorm.DB, *gin.Engine, *waffout
t.Setenv("WAFFO_WEBHOOK_PUBLIC_KEY", "")
t.Setenv("WAFFO_WEBHOOK_TEST_PUBLIC_KEY", platform.PublicKey)
t.Setenv("WAFFO_WEBHOOK_PROD_PUBLIC_KEY", merchant.PublicKey)
oldEnabled, oldSandbox, oldMerchant := setting.WaffoEnabled, setting.WaffoSandbox, setting.WaffoMerchantId
oldMerchant := setting.WaffoMerchantId
oldAPIKey, oldPrivateKey, oldPublicKey := setting.WaffoApiKey, setting.WaffoPrivateKey, setting.WaffoPublicCert
oldPancakeMerchant, oldPancakeKey := setting.WaffoPancakeMerchantID, setting.WaffoPancakePrivateKey
oldProduct, oldStore := setting.WaffoPancakeProductID, setting.WaffoPancakeStoreID
oldDB, oldLogDB := model.DB, model.LOG_DB
oldType, oldRedis, oldBatch, oldQuota := common.MainDatabaseType(), common.RedisEnabled, common.BatchUpdateEnabled, common.QuotaPerUnit
db, err := gorm.Open(sqlite.Open("file:"+url.QueryEscape(t.Name())+"?mode=memory&cache=shared"), &gorm.Config{})
require.NoError(t, err)
connection, err := db.DB()
require.NoError(t, err)
// Subscription completion also reads the plan and DB timestamp outside its
// transaction, so those reads need another connection to the same test DB.
connection.SetMaxOpenConns(4)
model.DB, model.LOG_DB = db, db
common.SetMainDatabaseType(common.DatabaseTypeSQLite)
common.RedisEnabled, common.BatchUpdateEnabled, common.QuotaPerUnit = false, false, 500_000
setting.WaffoEnabled, setting.WaffoSandbox, setting.WaffoMerchantId = true, false, "receipt-merchant"
setting.WaffoApiKey, setting.WaffoPrivateKey, setting.WaffoPublicCert = "receipt-api-key", merchant.PrivateKey, platform.PublicKey
setting.WaffoPancakeMerchantID, setting.WaffoPancakePrivateKey = "receipt-merchant", merchant.PrivateKey
setting.WaffoPancakeProductID, setting.WaffoPancakeStoreID = "receipt-product", "receipt-store"
t.Cleanup(func() {
setting.WaffoEnabled, setting.WaffoSandbox, setting.WaffoMerchantId = oldEnabled, oldSandbox, oldMerchant
setting.WaffoMerchantId = oldMerchant
setting.WaffoApiKey, setting.WaffoPrivateKey, setting.WaffoPublicCert = oldAPIKey, oldPrivateKey, oldPublicKey
setting.WaffoPancakeMerchantID, setting.WaffoPancakePrivateKey = oldPancakeMerchant, oldPancakeKey
setting.WaffoPancakeProductID, setting.WaffoPancakeStoreID = oldProduct, oldStore
model.DB, model.LOG_DB = oldDB, oldLogDB
common.SetMainDatabaseType(oldType)
common.RedisEnabled, common.BatchUpdateEnabled, common.QuotaPerUnit = oldRedis, oldBatch, oldQuota
assert.NoError(t, connection.Close())
})
models := append([]any{&model.User{}, &model.TopUp{}, &model.Redemption{}, &model.SubscriptionOrder{}, &model.SubscriptionPlan{}, &model.UserSubscription{}, &model.Log{}, &model.PaymentReceipt{}}, model.UserOperationModels()...)
require.NoError(t, db.AutoMigrate(models...))
models := append([]any{&model.User{}, &model.Redemption{}, &model.SubscriptionPlan{}, &model.UserSubscription{}, &model.Log{}, &model.PaymentReceipt{}}, model.UserOperationModels()...)
db := setupPaymentWebhookDB(t, models...)
require.NoError(t, model.UpdateOptionsBulk(map[string]string{
"WaffoMerchantId": "receipt-merchant", "WaffoApiKey": "receipt-api-key", "WaffoPrivateKey": merchant.PrivateKey, "WaffoPublicCert": platform.PublicKey,
"WaffoPancakeMerchantID": "receipt-merchant", "WaffoPancakePrivateKey": merchant.PrivateKey,
"WaffoPancakeProductID": "receipt-product", "WaffoPancakeStoreID": "receipt-store",
}))
revisions := map[string]int{
model.PaymentProviderWaffo: stoppedWebhookRevision(t, model.PaymentProviderWaffo).RevisionID,
model.PaymentProviderWaffoPancake: stoppedWebhookRevision(t, model.PaymentProviderWaffoPancake).RevisionID,
}
require.NoError(t, db.Create(&model.UserAnnualLevelEpoch{ID: 1}).Error)
_, err = model.SaveUserCreditConfig(model.DefaultUserCreditConfig())
require.NoError(t, err)
router := gin.New()
router.POST("/waffo", WaffoWebhook)
router.POST("/waffo_pancake/:env", WaffoPancakeWebhook)
return db, router, platform, merchant
return db, router, platform, merchant, revisions
}
func signWaffoPaymentWebhookForTest(t *testing.T, provider, body, privateKey string, timestamp int64) string {
@@ -729,7 +598,7 @@ func signWaffoPaymentWebhookForTest(t *testing.T, provider, body, privateKey str
}
func TestWaffoVerifiedPaymentWebhookReceipts(t *testing.T) {
db, router, platform, merchant := setupWaffoPaymentWebhookTest(t)
db, router, platform, merchant, revisions := setupWaffoPaymentWebhookTest(t)
plan := model.SubscriptionPlan{Id: 9_600_001, Title: "Receipt plan", PriceAmount: 2, Currency: "USD", DurationUnit: "day", DurationValue: 1, TotalAmount: 700, Enabled: true}
require.NoError(t, db.Create(&plan).Error)
model.InvalidateSubscriptionPlanCache(plan.Id)
@@ -766,9 +635,9 @@ func TestWaffoVerifiedPaymentWebhookReceipts(t *testing.T) {
}
}
require.NoError(t, db.Create(&model.User{Id: userID, Username: tradeNo, AffCode: tradeNo, Status: common.UserStatusEnabled, Group: "default", Quota: 37}).Error)
order := model.TopUp{UserId: userID, TradeNo: tradeNo, Amount: 100, Money: 2, PaymentProvider: target.provider, PaymentMethod: target.provider, Status: common.TopUpStatusPending}
order := model.TopUp{UserId: userID, TradeNo: tradeNo, Amount: 100, Money: 2, PaymentProvider: target.provider, PaymentMethod: target.provider, Status: common.TopUpStatusPending, PaymentCredentialRevisionID: revisions[target.provider]}
if target.kind == "subscription" {
require.NoError(t, db.Create(&model.SubscriptionOrder{UserId: userID, PlanId: plan.Id, TradeNo: tradeNo, Money: 2, PaymentProvider: target.provider, PaymentMethod: target.provider, Status: common.TopUpStatusPending}).Error)
require.NoError(t, db.Create(&model.SubscriptionOrder{UserId: userID, PlanId: plan.Id, TradeNo: tradeNo, Money: 2, PaymentProvider: target.provider, PaymentMethod: target.provider, Status: common.TopUpStatusPending, PaymentCredentialRevisionID: revisions[target.provider]}).Error)
} else {
require.NoError(t, db.Create(&order).Error)
}
@@ -793,11 +662,13 @@ func TestWaffoVerifiedPaymentWebhookReceipts(t *testing.T) {
data := map[string]any{"merchantOrderId": tradeNo, "paymentRequestId": tradeNo, "orderStatus": "PAY_SUCCESS", "orderCurrency": "USD", "orderAmount": "2.00", "userCurrency": tc.currency,
"merchantInfo": map[string]any{"merchantId": setting.WaffoMerchantId}}
payload := map[string]any{"eventType": "PAYMENT_NOTIFICATION", "result": data}
key := platform.PrivateKey
path, header, amountKey, source := "/waffo", "X-SIGNATURE", "finalDealAmount", "waffo.finalDealAmount"
if target.provider == model.PaymentProviderWaffoPancake {
data = map[string]any{"orderId": "ORD_provider_internal_only", "orderMerchantExternalId": tradeNo, "merchantProvidedBuyerIdentity": fmt.Sprintf("new-api-user-%d", userID), "currency": tc.currency, "amount": "29.00", "taxAmount": "1.34", "subtotal": "30.00"}
payload = map[string]any{"id": "receipt-event-" + tradeNo, "eventId": "PAY_provider_internal_only", "eventType": "order.completed", "storeId": setting.WaffoPancakeStoreID, "mode": "test", "data": data}
path, header, amountKey, source = "/waffo_pancake/test", "X-Waffo-Signature", "total", "waffo_pancake.total"
payload = map[string]any{"id": "receipt-event-" + tradeNo, "eventId": "PAY_provider_internal_only", "eventType": "order.completed", "storeId": setting.WaffoPancakeStoreID, "mode": "prod", "data": data}
key = merchant.PrivateKey
path, header, amountKey, source = "/waffo_pancake/prod", "X-Waffo-Signature", "total", "waffo_pancake.total"
}
missingAmount := tc.missingAmount || tc.nullAmount || (tc.lateAmount && attempt == 0)
if tc.nullAmount {
@@ -813,7 +684,7 @@ func TestWaffoVerifiedPaymentWebhookReceipts(t *testing.T) {
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, path, strings.NewReader(string(body)))
request.Header.Set("Content-Type", "application/json")
request.Header.Set(header, signWaffoPaymentWebhookForTest(t, target.provider, string(body), platform.PrivateKey, time.Now().UnixMilli()))
request.Header.Set(header, signWaffoPaymentWebhookForTest(t, target.provider, string(body), key, time.Now().UnixMilli()))
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, request)
transactionFailed := failTable != ""
@@ -913,7 +784,7 @@ func TestWaffoVerifiedPaymentWebhookReceipts(t *testing.T) {
}
func TestWaffoPaymentWebhooksRejectInvalidEvidence(t *testing.T) {
db, router, platform, merchant := setupWaffoPaymentWebhookTest(t)
db, router, platform, merchant, revisions := setupWaffoPaymentWebhookTest(t)
userID := 3100
for _, target := range []struct {
provider, kind string
@@ -926,10 +797,10 @@ func TestWaffoPaymentWebhooksRejectInvalidEvidence(t *testing.T) {
"missing signature", "malformed signature", "wrong signing key", "tampered amount", "tampered order",
"wrong provider", "missing order reference", "unknown order", "unrelated event", "invalid actual amount",
"wrong merchant", "wrong payment request", "optional Waffo metadata absent", "closed order",
"stale timestamp", "changed timestamp", "wrong buyer", "missing buyer", "wrong store", "wrong environment",
"stale timestamp", "changed timestamp", "wrong buyer", "missing buyer", "wrong store", "wrong environment", "signed test event",
} {
waffoOnly := scenario == "wrong merchant" || scenario == "wrong payment request" || scenario == "optional Waffo metadata absent" || scenario == "closed order"
pancakeOnly := scenario == "stale timestamp" || scenario == "changed timestamp" || scenario == "wrong buyer" || scenario == "missing buyer" || scenario == "wrong store" || scenario == "wrong environment"
pancakeOnly := scenario == "stale timestamp" || scenario == "changed timestamp" || scenario == "wrong buyer" || scenario == "missing buyer" || scenario == "wrong store" || scenario == "wrong environment" || scenario == "signed test event"
if (waffoOnly && target.provider != model.PaymentProviderWaffo) || (pancakeOnly && target.provider != model.PaymentProviderWaffoPancake) {
continue
}
@@ -953,9 +824,9 @@ func TestWaffoPaymentWebhooksRejectInvalidEvidence(t *testing.T) {
provider = model.PaymentProviderStripe
}
if target.kind == "subscription" {
require.NoError(t, db.Create(&model.SubscriptionOrder{UserId: userID, TradeNo: tradeNo, PaymentProvider: provider, PaymentMethod: provider, Status: common.TopUpStatusPending}).Error)
require.NoError(t, db.Create(&model.SubscriptionOrder{UserId: userID, TradeNo: tradeNo, PaymentProvider: provider, PaymentMethod: provider, Status: common.TopUpStatusPending, PaymentCredentialRevisionID: revisions[provider]}).Error)
} else {
require.NoError(t, db.Create(&model.TopUp{UserId: userID, TradeNo: tradeNo, Amount: 100, Money: 2, PaymentProvider: provider, PaymentMethod: provider, Status: common.TopUpStatusPending}).Error)
require.NoError(t, db.Create(&model.TopUp{UserId: userID, TradeNo: tradeNo, Amount: 100, Money: 2, PaymentProvider: provider, PaymentMethod: provider, Status: common.TopUpStatusPending, PaymentCredentialRevisionID: revisions[provider]}).Error)
}
data := map[string]any{"merchantOrderId": tradeNo, "paymentRequestId": tradeNo, "orderStatus": "PAY_SUCCESS", "finalDealAmount": "12.34", "userCurrency": "EUR", "merchantInfo": map[string]any{"merchantId": setting.WaffoMerchantId}}
payload := map[string]any{"eventType": "PAYMENT_NOTIFICATION", "result": data}
@@ -964,8 +835,8 @@ func TestWaffoPaymentWebhooksRejectInvalidEvidence(t *testing.T) {
// An internal orderId equal to a local trade_no must never be
// used as a fallback when the external order binding is absent.
data = map[string]any{"orderId": tradeNo, "orderMerchantExternalId": tradeNo, "merchantProvidedBuyerIdentity": fmt.Sprintf("new-api-user-%d", userID), "total": "12.34", "currency": "EUR", "amount": "2.00"}
payload = map[string]any{"id": "rejected-event-" + tradeNo, "eventType": "order.completed", "storeId": setting.WaffoPancakeStoreID, "mode": "test", "data": data}
path, header, amountKey, orderKey = "/waffo_pancake/test", "X-Waffo-Signature", "total", "orderMerchantExternalId"
payload = map[string]any{"id": "rejected-event-" + tradeNo, "eventType": "order.completed", "storeId": setting.WaffoPancakeStoreID, "mode": "prod", "data": data}
path, header, amountKey, orderKey = "/waffo_pancake/prod", "X-Waffo-Signature", "total", "orderMerchantExternalId"
}
switch scenario {
case "missing order reference":
@@ -991,13 +862,19 @@ func TestWaffoPaymentWebhooksRejectInvalidEvidence(t *testing.T) {
delete(data, "merchantProvidedBuyerIdentity")
case "wrong store":
payload["storeId"] = "another-store"
case "wrong environment":
payload["mode"] = "prod"
case "wrong environment", "signed test event":
payload["mode"] = "test"
if scenario == "signed test event" {
path = "/waffo_pancake/test"
}
}
bodyBytes, err := common.Marshal(payload)
require.NoError(t, err)
body := string(bodyBytes)
timestamp, key := time.Now().UnixMilli(), platform.PrivateKey
if target.provider == model.PaymentProviderWaffoPancake && payload["mode"] == "prod" {
key = merchant.PrivateKey
}
if scenario == "stale timestamp" {
timestamp -= 10 * 60 * 1000
}
@@ -1035,14 +912,15 @@ func TestWaffoPaymentWebhooksRejectInvalidEvidence(t *testing.T) {
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, request)
accepted := scenario == "optional Waffo metadata absent"
if signatureRejected {
noKnownOrder := scenario == "wrong provider" || scenario == "missing order reference" || scenario == "unknown order"
if noKnownOrder || scenario == "wrong store" || scenario == "signed test event" || (target.provider == model.PaymentProviderWaffo && scenario == "tampered order") {
assert.Equal(t, http.StatusForbidden, recorder.Code)
} else if signatureRejected {
status := http.StatusBadRequest
if target.provider == model.PaymentProviderWaffoPancake {
status = http.StatusUnauthorized
}
assert.Equal(t, status, recorder.Code)
} else if scenario == "wrong store" {
assert.Equal(t, http.StatusUnauthorized, recorder.Code)
} else if target.provider == model.PaymentProviderWaffoPancake && scenario == "invalid actual amount" {
assert.Equal(t, http.StatusInternalServerError, recorder.Code)
assert.Equal(t, "retry", recorder.Body.String())
@@ -1093,25 +971,17 @@ func TestWaffoPaymentWebhooksRejectInvalidEvidence(t *testing.T) {
}
func TestUpdateOptionValidatesEpaySignSettings(t *testing.T) {
db := setupModelListControllerTestDB(t)
require.NoError(t, db.AutoMigrate(&model.Option{}))
originalOptionMap := common.OptionMap
setupPaymentWebhookDB(t)
paymentSetting := operation_setting.GetPaymentSetting()
originalSignType := paymentSetting.EpaySignType
originalMerchantPrivateKey := paymentSetting.EpayMerchantPrivateKey
originalPlatformPublicKey := paymentSetting.EpayPlatformPublicKey
t.Cleanup(func() {
common.OptionMap = originalOptionMap
paymentSetting.EpaySignType = originalSignType
paymentSetting.EpayMerchantPrivateKey = originalMerchantPrivateKey
paymentSetting.EpayPlatformPublicKey = originalPlatformPublicKey
})
// A site upgraded from an MD5-only release has no saved RSA settings.
common.OptionMap = map[string]string{
operation_setting.EpaySignTypeOptionKey: operation_setting.EpaySignTypeMD5,
operation_setting.EpayMerchantPrivateKeyOptionKey: "",
operation_setting.EpayPlatformPublicKeyOptionKey: "",
}
paymentSetting.EpaySignType = operation_setting.EpaySignTypeMD5
paymentSetting.EpayMerchantPrivateKey = ""
paymentSetting.EpayPlatformPublicKey = ""
@@ -1154,7 +1024,7 @@ func TestUpdateOptionValidatesEpaySignSettings(t *testing.T) {
assert.Equal(t, merchantPrivateKey, paymentSetting.EpayMerchantPrivateKey)
assert.Equal(t, platformPublicKey, paymentSetting.EpayPlatformPublicKey)
// The private key is never sent back to the settings page; the public key may be.
// Signing credentials are write-only in the settings API.
recorder := httptest.NewRecorder()
context, _ := gin.CreateTestContext(recorder)
context.Request = httptest.NewRequest(http.MethodGet, "/api/option/", nil)
@@ -1170,6 +1040,6 @@ func TestUpdateOptionValidatesEpaySignSettings(t *testing.T) {
returned[option.Key] = option.Value
}
assert.Equal(t, operation_setting.EpaySignTypeMD5, returned[signTypeKey])
assert.Equal(t, platformPublicKey, returned[publicKeyKey])
assert.NotContains(t, returned, publicKeyKey)
assert.NotContains(t, returned, privateKeyKey)
}
+3 -21
View File
@@ -25,7 +25,6 @@ import (
relayconstant "github.com/QuantumNous/new-api/relay/constant"
"github.com/QuantumNous/new-api/relay/helper"
"github.com/QuantumNous/new-api/relay/requestplugin"
"github.com/QuantumNous/new-api/relaykit/dto"
"github.com/QuantumNous/new-api/relaykit/types"
"github.com/QuantumNous/new-api/service"
"github.com/QuantumNous/new-api/setting/operation_setting"
@@ -109,7 +108,7 @@ func Relay(c *gin.Context, relayFormat types.RelayFormat) {
upstreamURLs := common.UpstreamAddresses(c)
if relayFormat != types.RelayFormatOpenAIRealtime && c.Writer.Written() &&
strings.HasPrefix(c.Writer.Header().Get("Content-Type"), "text/event-stream") {
writeRelayStreamError(c, relayFormat, newAPIError)
helper.StreamErrorData(c, relayFormat, newAPIError)
return
}
if relayFormat != types.RelayFormatOpenAIRealtime {
@@ -195,7 +194,7 @@ func Relay(c *gin.Context, relayFormat types.RelayFormat) {
Ctx: c,
TokenGroup: relayInfo.TokenGroup,
ModelName: relayInfo.OriginModelName,
RequestPath: c.Request.URL.Path,
RequestPath: common.NormalizeRelayPath(c.Request.URL.Path),
Retry: common.GetPointer(0),
}
relayInfo.RetryIndex = 0
@@ -270,23 +269,6 @@ func Relay(c *gin.Context, relayFormat types.RelayFormat) {
}
}
func writeRelayStreamError(c *gin.Context, format types.RelayFormat, apiError *types.NewAPIError) {
// 心跳提交响应头后,最终错误继续通过同一个流返回。
status, _ := common.GetContextKeyType[*relaycommon.StreamStatus](c, constant.ContextKeyResponseStreamStatus)
if status == nil {
status = relaycommon.NewStreamStatus()
common.SetContextKey(c, constant.ContextKeyResponseStreamStatus, status)
}
status.MarkFailed(string(apiError.GetErrorCode()), string(apiError.GetErrorType()), apiError.StatusCode)
upstreamURLs := common.UpstreamAddresses(c)
if format == types.RelayFormatClaude {
_ = helper.ClaudeData(c, dto.ClaudeResponse{Type: "error", Error: apiError.ToClaudeError(upstreamURLs...)})
return
}
_ = helper.ObjectData(c, gin.H{"error": apiError.ToOpenAIError(upstreamURLs...)})
helper.Done(c)
}
// CountClaudeTokens implements Anthropic's token-counting utility endpoint.
// It deliberately skips upstream generation and billing; callers use this
// endpoint to size prompts before creating a Message.
@@ -661,7 +643,7 @@ func executeTaskSubmissionWith(
Ctx: c,
TokenGroup: relayInfo.TokenGroup,
ModelName: relayInfo.OriginModelName,
RequestPath: c.Request.URL.Path,
RequestPath: common.NormalizeRelayPath(c.Request.URL.Path),
Retry: common.GetPointer(0),
}
+1 -1
View File
@@ -283,7 +283,7 @@ func TestRelayStreamErrorAfterKeepAlive(t *testing.T) {
common.SetContextKey(c, constant.ContextKeyChannelBaseUrl, "https://provider.example")
common.SetContextKey(c, constant.ContextKeyUpstreamRequestOrigin, "https://provider.example")
apiError := types.NewErrorWithStatusCode(errors.New("upstream rejected input at https://provider.example/v1/messages"), types.ErrorCodeBadResponseStatusCode, http.StatusBadRequest)
writeRelayStreamError(c, format, apiError)
helper.StreamErrorData(c, format, apiError)
require.Equal(t, http.StatusOK, recorder.Code)
require.Equal(t, "text/event-stream", recorder.Header().Get("Content-Type"))
require.Contains(t, recorder.Body.String(), "upstream rejected input")
+4 -5
View File
@@ -9,7 +9,6 @@ import (
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/logger"
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/setting"
"github.com/QuantumNous/new-api/setting/operation_setting"
"github.com/gin-gonic/gin"
"github.com/thanhpk/randstr"
@@ -53,7 +52,7 @@ func SubscriptionRequestCreemPay(c *gin.Context) {
common.ApiErrorT(c, "CreemProductId is not configured for this plan")
return
}
if setting.CreemWebhookSecret == "" && !setting.CreemTestMode {
if checkoutGateway(c).Values["CreemWebhookSecret"] == "" {
common.ApiErrorT(c, "Creem webhook is not configured")
return
}
@@ -95,8 +94,8 @@ func SubscriptionRequestCreemPay(c *gin.Context) {
CreateTime: time.Now().Unix(),
Status: common.TopUpStatusPending,
}
if err := order.Insert(); err != nil {
paymentError(c, common.NewMessage("Failed to create order"))
if err := order.InsertGatewayOrder(checkoutGateway(c).RevisionID); err != nil {
paymentGatewayOrderError(c, err)
return
}
@@ -118,7 +117,7 @@ func SubscriptionRequestCreemPay(c *gin.Context) {
Quota: 0,
}
checkoutUrl, err := genCreemLink(c.Request.Context(), referenceId, product, user.Email, user.Username)
checkoutUrl, err := genCreemLink(c.Request.Context(), referenceId, product, user.Email, user.Username, checkoutGateway(c))
if err != nil {
logger.LogError(c.Request.Context(), common.LogText("Creem failed to create subscription payment link trade_no=%s product_id=%s error=%q", referenceId, product.ProductId, err.Error()))
paymentError(c, common.NewMessage("Failed to start payment"))
+7 -6
View File
@@ -45,7 +45,8 @@ func SubscriptionRequestEpay(c *gin.Context) {
common.ApiErrorT(c, "Plan amount is too low")
return
}
if _, available := epayPaymentMethod(req.PaymentMethod); !isEpayTopUpEnabled() || !available {
config := checkoutGateway(c).Values
if _, available := findEpayMethod(epayConfiguredMethods(config["PayMethods"]), req.PaymentMethod); !available {
common.ApiErrorT(c, "Payment method does not exist")
return
}
@@ -78,7 +79,7 @@ func SubscriptionRequestEpay(c *gin.Context) {
tradeNo := fmt.Sprintf("%s%d", common.GetRandomString(6), time.Now().Unix())
tradeNo = fmt.Sprintf("SUBUSR%dNO%s", userId, tradeNo)
client := GetEpayClient()
client := epayClientForConfig(config)
if client == nil {
common.ApiErrorT(c, "Payment information has not been configured by administrator")
return
@@ -94,8 +95,8 @@ func SubscriptionRequestEpay(c *gin.Context) {
CreateTime: time.Now().Unix(),
Status: common.TopUpStatusPending,
}
if err := order.Insert(); err != nil {
common.ApiErrorT(c, "Failed to create order")
if err := order.InsertGatewayOrder(checkoutGateway(c).RevisionID); err != nil {
paymentGatewayOrderError(c, err)
return
}
uri, params, err := client.Purchase(&epay.PurchaseArgs{
@@ -141,7 +142,7 @@ func SubscriptionEpayNotify(c *gin.Context) {
return
}
client := GetEpayClient()
client := epayOrderClient(params["out_trade_no"], true)
if client == nil {
_, _ = c.Writer.Write([]byte("fail"))
return
@@ -201,7 +202,7 @@ func SubscriptionEpayReturn(c *gin.Context) {
return
}
client := GetEpayClient()
client := epayOrderClient(params["out_trade_no"], true)
if client == nil {
c.Redirect(http.StatusFound, paymentReturnPath("/wallet?pay=fail"))
return
+15 -15
View File
@@ -9,7 +9,6 @@ import (
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/logger"
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/setting"
"github.com/gin-gonic/gin"
"github.com/stripe/stripe-go/v81"
"github.com/stripe/stripe-go/v81/checkout/session"
@@ -44,11 +43,11 @@ func SubscriptionRequestStripePay(c *gin.Context) {
common.ApiErrorT(c, "StripePriceId is not configured for this plan")
return
}
if !strings.HasPrefix(setting.StripeApiSecret, "sk_") && !strings.HasPrefix(setting.StripeApiSecret, "rk_") {
if !strings.HasPrefix(checkoutGateway(c).Values["StripeApiSecret"], "sk_") && !strings.HasPrefix(checkoutGateway(c).Values["StripeApiSecret"], "rk_") {
common.ApiErrorT(c, "Stripe is not configured or key is invalid")
return
}
if setting.StripeWebhookSecret == "" {
if checkoutGateway(c).Values["StripeWebhookSecret"] == "" {
common.ApiErrorT(c, "Stripe webhook is not configured")
return
}
@@ -79,13 +78,6 @@ func SubscriptionRequestStripePay(c *gin.Context) {
reference := fmt.Sprintf("sub-stripe-ref-%d-%d-%s", user.Id, time.Now().UnixMilli(), randstr.String(4))
referenceId := "sub_ref_" + common.Sha1([]byte(reference))
payLink, err := genStripeSubscriptionLink(referenceId, user.StripeCustomer, user.Email, plan.StripePriceId)
if err != nil {
logger.LogError(c.Request.Context(), common.LogText("Stripe failed to create subscription payment link trade_no=%s plan_id=%d error=%q", referenceId, plan.Id, err.Error()))
paymentError(c, common.NewMessage("Failed to start payment"))
return
}
order := &model.SubscriptionOrder{
UserId: userId,
PlanId: plan.Id,
@@ -96,8 +88,15 @@ func SubscriptionRequestStripePay(c *gin.Context) {
CreateTime: time.Now().Unix(),
Status: common.TopUpStatusPending,
}
if err := order.Insert(); err != nil {
paymentError(c, common.NewMessage("Failed to create order"))
if err := order.InsertGatewayOrder(checkoutGateway(c).RevisionID); err != nil {
paymentGatewayOrderError(c, err)
return
}
payLink, err := genStripeSubscriptionLink(referenceId, user.StripeCustomer, user.Email, plan.StripePriceId, checkoutGateway(c))
if err != nil {
logger.LogError(c.Request.Context(), common.LogText("Stripe failed to create subscription payment link trade_no=%s plan_id=%d error=%q", referenceId, plan.Id, err.Error()))
paymentError(c, common.NewMessage("Failed to start payment"))
return
}
@@ -109,8 +108,7 @@ func SubscriptionRequestStripePay(c *gin.Context) {
})
}
func genStripeSubscriptionLink(referenceId string, customerId string, email string, priceId string) (string, error) {
stripe.Key = setting.StripeApiSecret
func genStripeSubscriptionLink(referenceId string, customerId string, email string, priceId string, config model.PaymentGatewayConfiguration) (string, error) {
params := &stripe.CheckoutSessionParams{
ClientReferenceID: stripe.String(referenceId),
@@ -134,7 +132,9 @@ func genStripeSubscriptionLink(referenceId string, customerId string, email stri
params.Customer = stripe.String(customerId)
}
result, err := session.New(params)
client := session.Client{B: stripe.GetBackend(stripe.APIBackend), Key: config.Values["StripeApiSecret"]}
result, err := client.New(params)
stopRejectedPaymentGateway(model.PaymentProviderStripe, config.RevisionID, err)
if err != nil {
return "", err
}
@@ -10,7 +10,6 @@ import (
"github.com/QuantumNous/new-api/logger"
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/service"
"github.com/QuantumNous/new-api/setting"
"github.com/gin-gonic/gin"
"github.com/shopspring/decimal"
"github.com/thanhpk/randstr"
@@ -44,13 +43,7 @@ func SubscriptionRequestWaffoPancakePay(c *gin.Context) {
common.ApiErrorT(c, "WaffoPancakeProductId is not configured for this plan")
return
}
// Plan targets its own Pancake product, so we only require credentials
// here — not the gateway-level WaffoPancakeProductID.
if strings.TrimSpace(setting.WaffoPancakeMerchantID) == "" ||
strings.TrimSpace(setting.WaffoPancakePrivateKey) == "" {
common.ApiErrorT(c, "Waffo Pancake is not configured or key is invalid")
return
}
config := checkoutGateway(c)
userId := c.GetInt("id")
user, err := model.GetUserById(userId, false)
@@ -89,9 +82,9 @@ func SubscriptionRequestWaffoPancakePay(c *gin.Context) {
CreateTime: time.Now().Unix(),
Status: common.TopUpStatusPending,
}
if err := order.Insert(); err != nil {
if err := order.InsertGatewayOrder(checkoutGateway(c).RevisionID); err != nil {
logger.LogError(c.Request.Context(), common.LogText("Waffo Pancake failed to create subscription order user_id=%d plan_id=%d trade_no=%s error=%q", userId, plan.Id, tradeNo, err.Error()))
paymentError(c, common.NewMessage("Failed to create order"))
paymentGatewayOrderError(c, err)
return
}
@@ -106,7 +99,8 @@ func SubscriptionRequestWaffoPancakePay(c *gin.Context) {
BuyerEmail: getWaffoPancakeBuyerEmail(user),
ExpiresInSeconds: &expiresInSeconds,
OrderMerchantExternalID: tradeNo,
})
}, config.Values["WaffoPancakeMerchantID"], config.Values["WaffoPancakePrivateKey"])
stopRejectedPaymentGateway(model.PaymentProviderWaffoPancake, config.RevisionID, err)
if err != nil {
logger.LogError(c.Request.Context(), common.LogText("Waffo Pancake failed to create subscription checkout session user_id=%d plan_id=%d trade_no=%s error=%q", userId, plan.Id, tradeNo, err.Error()))
order.Status = common.TopUpStatusFailed
+62 -49
View File
@@ -27,19 +27,26 @@ import (
func GetTopUpInfo(c *gin.Context) {
complianceConfirmed := operation_setting.IsPaymentComplianceConfirmed()
epayMethods := []map[string]string{}
if complianceConfirmed && isEpayWebhookConfigured() {
epayMethods = epayPaymentMethods()
}
epayConfig := activePaymentGateway(model.PaymentProviderEpay, false)
epayMethods := epayConfiguredMethods(epayConfig.Values["PayMethods"])
stripeConfig := activePaymentGateway(model.PaymentProviderStripe, true)
creemConfig := activePaymentGateway(model.PaymentProviderCreem, true)
waffoConfig := activePaymentGateway(model.PaymentProviderWaffo, false)
pancakeConfig := activePaymentGateway(model.PaymentProviderWaffoPancake, true)
enableStripe, enableCreem := stripeConfig.RevisionID > 0, creemConfig.RevisionID > 0
enableWaffo, enableWaffoPancake := waffoConfig.RevisionID > 0, pancakeConfig.RevisionID > 0
stripeWallet := enableStripe && paymentGatewayConfigured(model.PaymentProviderStripe, stripeConfig.Values, false)
creemWallet := enableCreem && paymentGatewayConfigured(model.PaymentProviderCreem, creemConfig.Values, false)
pancakeWallet := enableWaffoPancake && paymentGatewayConfigured(model.PaymentProviderWaffoPancake, pancakeConfig.Values, false)
payMethods := []map[string]string{}
for _, gateway := range []struct {
enabled bool
kind, name, color string
minimum int
}{
{isStripeTopUpEnabled(), model.PaymentMethodStripe, "Stripe", "#635BFF", setting.StripeMinTopUp},
{isWaffoPancakeTopUpEnabled(), model.PaymentMethodWaffoPancake, "Waffo Pancake", "#F97316", setting.WaffoPancakeMinTopUp},
{isWaffoTopUpEnabled(), model.PaymentMethodWaffo, "Waffo (Global Payment)", "#3B82F6", setting.WaffoMinTopUp},
{stripeWallet, model.PaymentMethodStripe, "Stripe", "#635BFF", setting.StripeMinTopUp},
{pancakeWallet, model.PaymentMethodWaffoPancake, "Waffo Pancake", "#F97316", setting.WaffoPancakeMinTopUp},
{enableWaffo, model.PaymentMethodWaffo, "Waffo (Global Payment)", "#3B82F6", setting.WaffoMinTopUp},
} {
if !gateway.enabled {
continue
@@ -54,30 +61,31 @@ func GetTopUpInfo(c *gin.Context) {
}
payMethods = append(payMethods, method)
}
enableWaffo := isWaffoTopUpEnabled()
enableWaffoPancake := isWaffoPancakeTopUpEnabled()
alipayEnabled, alipayMinimum := alipayDirectAvailability()
amountOptions, customAmount := operation_setting.GetTopUpAmountSettings()
data := gin.H{
"enable_online_topup": len(epayMethods) > 0,
"epay_pay_methods": epayPaymentMethodsForWallet(epayMethods),
"enable_alipay_direct": alipayEnabled,
"alipay_direct_min_topup": alipayMinimum,
"enable_stripe_topup": isStripeTopUpEnabled(),
"enable_creem_topup": isCreemTopUpEnabled(),
"enable_waffo_topup": enableWaffo,
"enable_waffo_pancake_topup": enableWaffoPancake,
"enable_redemption": complianceConfirmed,
"payment_compliance_confirmed": complianceConfirmed,
"payment_compliance_terms_version": operation_setting.CurrentComplianceTermsVersion,
"enable_online_topup": len(epayMethods) > 0,
"epay_pay_methods": epayPaymentMethodsForWallet(epayMethods),
"enable_alipay_direct": alipayEnabled,
"alipay_direct_min_topup": alipayMinimum,
"enable_stripe_topup": stripeWallet,
"enable_creem_topup": creemWallet,
"enable_waffo_topup": enableWaffo,
"enable_waffo_pancake_topup": pancakeWallet,
"enable_stripe_subscription": enableStripe,
"enable_creem_subscription": enableCreem,
"enable_waffo_pancake_subscription": enableWaffoPancake,
"enable_redemption": complianceConfirmed,
"payment_compliance_confirmed": complianceConfirmed,
"payment_compliance_terms_version": operation_setting.CurrentComplianceTermsVersion,
"waffo_pay_methods": func() any {
if enableWaffo {
return setting.GetWaffoPayMethods()
}
return nil
}(),
"creem_products": setting.CreemProducts,
"creem_products": creemConfig.Values["CreemProducts"],
"pay_methods": payMethods,
"min_topup": getMinTopup(),
"stripe_min_topup": setting.StripeMinTopUp,
@@ -101,25 +109,40 @@ type AmountRequest struct {
}
func GetEpayClient() *epay.Client {
if operation_setting.PayAddress == "" || operation_setting.EpayId == "" {
payment := operation_setting.GetPaymentSetting()
return epayClientForConfig(map[string]string{
"PayAddress": operation_setting.PayAddress, "EpayId": operation_setting.EpayId, "EpayKey": operation_setting.EpayKey,
operation_setting.EpaySignTypeOptionKey: payment.EpaySignType,
operation_setting.EpayMerchantPrivateKeyOptionKey: payment.EpayMerchantPrivateKey,
operation_setting.EpayPlatformPublicKeyOptionKey: payment.EpayPlatformPublicKey,
})
}
func epayClientForConfig(values map[string]string) *epay.Client {
if values["PayAddress"] == "" || values["EpayId"] == "" {
return nil
}
config := &epay.Config{
PartnerID: operation_setting.EpayId,
Key: operation_setting.EpayKey,
}
if paymentSetting := operation_setting.GetPaymentSetting(); paymentSetting.EpaySignType == operation_setting.EpaySignTypeRSA {
config := &epay.Config{PartnerID: values["EpayId"], Key: values["EpayKey"]}
if values[operation_setting.EpaySignTypeOptionKey] == operation_setting.EpaySignTypeRSA {
config.SignType = epay.SignTypeRSA
config.MerchantPrivateKey = paymentSetting.EpayMerchantPrivateKey
config.PlatformPublicKey = paymentSetting.EpayPlatformPublicKey
} else if operation_setting.EpayKey == "" {
config.MerchantPrivateKey = values[operation_setting.EpayMerchantPrivateKeyOptionKey]
config.PlatformPublicKey = values[operation_setting.EpayPlatformPublicKeyOptionKey]
} else if config.Key == "" {
return nil
}
withUrl, err := epay.NewClient(config, operation_setting.PayAddress)
client, err := epay.NewClient(config, values["PayAddress"])
if err != nil {
return nil
}
return withUrl
return client
}
func epayOrderClient(tradeNo string, subscription bool) *epay.Client {
values, err := model.OrderPaymentGatewayConfiguration(model.PaymentProviderEpay, tradeNo, !subscription, subscription)
if err != nil {
return nil
}
return epayClientForConfig(values)
}
func epayCallbackPartnerMatches(client *epay.Client, params map[string]string) bool {
@@ -276,10 +299,7 @@ func rejectInvalidWalletTopUp(c *gin.Context, userId int, amount int64) bool {
}
func RequestEpay(c *gin.Context) {
if !isEpayTopUpEnabled() {
paymentError(c, common.NewMessage("Payment information has not been configured by administrator"))
return
}
config := checkoutGateway(c).Values
var req EpayRequest
err := c.ShouldBindJSON(&req)
if err != nil {
@@ -306,7 +326,7 @@ func RequestEpay(c *gin.Context) {
return
}
method, available := epayPaymentMethod(req.PaymentMethod)
method, available := findEpayMethod(epayConfiguredMethods(config["PayMethods"]), req.PaymentMethod)
if !available {
paymentError(c, common.NewMessage("Payment method does not exist"))
return
@@ -322,7 +342,7 @@ func RequestEpay(c *gin.Context) {
notifyUrl, _ := url.Parse(callBackAddress + "/api/user/epay/notify")
tradeNo := fmt.Sprintf("%s%d", common.GetRandomString(6), time.Now().Unix())
tradeNo = fmt.Sprintf("USR%dNO%s", id, tradeNo)
client := GetEpayClient()
client := epayClientForConfig(config)
if client == nil {
paymentError(c, common.NewMessage("Payment information has not been configured by administrator"))
return
@@ -357,13 +377,13 @@ func RequestEpay(c *gin.Context) {
CreateTime: time.Now().Unix(),
Status: common.TopUpStatusPending,
}
err = topUp.Insert()
err = topUp.InsertGatewayOrder(checkoutGateway(c).RevisionID)
if err != nil {
logger.LogError(c.Request.Context(), common.LogText("Epay failed to create top-up order user_id=%d trade_no=%s payment_method=%s amount=%d error=%q", id, tradeNo, req.PaymentMethod, req.Amount, err.Error()))
paymentError(c, common.NewMessage("Failed to create order"))
paymentGatewayOrderError(c, err)
return
}
logger.LogInfo(c.Request.Context(), common.LogText("Epay top-up order created user_id=%d trade_no=%s payment_method=%s amount=%d money=%.2f uri=%q params=%q", id, tradeNo, req.PaymentMethod, req.Amount, payMoney, uri, common.GetJsonString(params)))
logger.LogInfo(c.Request.Context(), common.LogText("Epay top-up order created user_id=%d trade_no=%s payment_method=%s amount=%d money=%.2f", id, tradeNo, req.PaymentMethod, req.Amount, payMoney))
c.JSON(http.StatusOK, gin.H{"message": "success", "data": params, "url": uri})
}
@@ -410,12 +430,6 @@ func UnlockOrder(tradeNo string) {
}
func EpayNotify(c *gin.Context) {
if !isEpayWebhookEnabled() {
logger.LogWarn(c.Request.Context(), common.LogText("Epay webhook rejected reason=webhook_disabled path=%q client_ip=%s", c.Request.RequestURI, c.ClientIP()))
_, _ = c.Writer.Write([]byte("fail"))
return
}
var params map[string]string
if c.Request.Method == "POST" {
@@ -436,14 +450,13 @@ func EpayNotify(c *gin.Context) {
return r
}, map[string]string{})
}
logger.LogInfo(c.Request.Context(), common.LogText("Epay webhook received request path=%q client_ip=%s method=%s params=%q", c.Request.RequestURI, c.ClientIP(), c.Request.Method, common.GetJsonString(params)))
if len(params) == 0 {
logger.LogWarn(c.Request.Context(), common.LogText("Epay webhook params are empty path=%q client_ip=%s", c.Request.RequestURI, c.ClientIP()))
_, _ = c.Writer.Write([]byte("fail"))
return
}
client := GetEpayClient()
client := epayOrderClient(params["out_trade_no"], false)
if client == nil {
logger.LogError(c.Request.Context(), common.LogText("Epay client is not initialized path=%q client_ip=%s", c.Request.RequestURI, c.ClientIP()))
_, err := c.Writer.Write([]byte("fail"))
+35 -53
View File
@@ -6,13 +6,11 @@ import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/logger"
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/setting"
"io"
"net/http"
"strconv"
@@ -37,11 +35,6 @@ func generateCreemSignature(payload string, secret string) string {
// 验证Creem webhook签名
func verifyCreemSignature(payload string, signature string, secret string) bool {
if secret == "" {
logger.LogWarn(context.Background(), common.LogText("Creem webhook secret is not configured test_mode=%t signature=%q body=%q", setting.CreemTestMode, signature, payload))
if setting.CreemTestMode {
logger.LogInfo(context.Background(), common.LogText("Creem webhook signature check skipped reason=test_mode signature=%q body=%q", signature, payload))
return true
}
return false
}
@@ -78,7 +71,7 @@ func (*CreemAdaptor) RequestPay(c *gin.Context, req *CreemPayRequest) {
// 解析产品列表
var products []CreemProduct
err := json.Unmarshal([]byte(setting.CreemProducts), &products)
err := common.UnmarshalJsonStr(checkoutGateway(c).Values["CreemProducts"], &products)
if err != nil {
logger.LogError(c.Request.Context(), common.LogText("Creem failed to parse product config user_id=%d error=%q", c.GetInt("id"), err.Error()))
paymentError(c, common.NewMessage("Product configuration error"))
@@ -125,15 +118,15 @@ func (*CreemAdaptor) RequestPay(c *gin.Context, req *CreemPayRequest) {
CreateTime: time.Now().Unix(),
Status: common.TopUpStatusPending,
}
err = topUp.Insert()
err = topUp.InsertGatewayOrder(checkoutGateway(c).RevisionID)
if err != nil {
logger.LogError(c.Request.Context(), common.LogText("Creem failed to create top-up order user_id=%d trade_no=%s product_id=%s error=%q", id, referenceId, selectedProduct.ProductId, err.Error()))
paymentError(c, common.NewMessage("Failed to create order"))
paymentGatewayOrderError(c, err)
return
}
// 创建支付链接,传入用户邮箱
checkoutUrl, err := genCreemLink(c.Request.Context(), referenceId, selectedProduct, user.Email, user.Username)
checkoutUrl, err := genCreemLink(c.Request.Context(), referenceId, selectedProduct, user.Email, user.Username, checkoutGateway(c))
if err != nil {
logger.LogError(c.Request.Context(), common.LogText("Creem failed to create payment link user_id=%d trade_no=%s product_id=%s error=%q", id, referenceId, selectedProduct.ProductId, err.Error()))
paymentError(c, common.NewMessage("Failed to start payment"))
@@ -162,8 +155,6 @@ func RequestCreemPay(c *gin.Context) {
return
}
logger.LogInfo(c.Request.Context(), common.LogText("Creem payment request received user_id=%d body=%q", c.GetInt("id"), string(bodyBytes)))
// 重新设置body供后续的ShouldBindJSON使用
c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes))
@@ -237,13 +228,6 @@ type CreemWebhookEvent struct {
}
func CreemWebhook(c *gin.Context) {
if !isCreemWebhookEnabled() {
logger.LogWarn(c.Request.Context(), common.LogText("Creem webhook rejected reason=webhook_disabled path=%q client_ip=%s", c.Request.RequestURI, c.ClientIP()))
c.AbortWithStatus(http.StatusForbidden)
return
}
// 读取body内容用于打印,同时保留原始数据供后续使用
bodyBytes, err := io.ReadAll(c.Request.Body)
if err != nil {
logger.LogError(c.Request.Context(), common.LogText("Creem webhook failed to read request body path=%q client_ip=%s error=%q", c.Request.RequestURI, c.ClientIP(), err.Error()))
@@ -251,31 +235,25 @@ func CreemWebhook(c *gin.Context) {
return
}
// 获取签名头
signature := c.GetHeader(CreemSignatureHeader)
logger.LogInfo(c.Request.Context(), common.LogText("Creem webhook received request path=%q client_ip=%s signature=%q body=%q", c.Request.RequestURI, c.ClientIP(), signature, string(bodyBytes)))
if signature == "" {
logger.LogWarn(c.Request.Context(), common.LogText("Creem webhook missing signature path=%q client_ip=%s body=%q", c.Request.RequestURI, c.ClientIP(), string(bodyBytes)))
c.AbortWithStatus(http.StatusUnauthorized)
return
}
// 验证签名
if !verifyCreemSignature(string(bodyBytes), signature, setting.CreemWebhookSecret) {
logger.LogWarn(c.Request.Context(), common.LogText("Creem webhook signature verification failed path=%q client_ip=%s signature=%q body=%q", c.Request.RequestURI, c.ClientIP(), signature, string(bodyBytes)))
c.AbortWithStatus(http.StatusUnauthorized)
return
}
logger.LogInfo(c.Request.Context(), common.LogText("Creem webhook signature verified path=%q client_ip=%s", c.Request.RequestURI, c.ClientIP()))
// 重新设置body供后续的ShouldBindJSON使用
c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes))
// 解析新格式的webhook数据
var webhookEvent CreemWebhookEvent
if err := c.ShouldBindJSON(&webhookEvent); err != nil {
logger.LogError(c.Request.Context(), common.LogText("Creem webhook failed to parse path=%q client_ip=%s error=%q body=%q", c.Request.RequestURI, c.ClientIP(), err.Error(), string(bodyBytes)))
if err := common.Unmarshal(bodyBytes, &webhookEvent); err != nil {
c.AbortWithStatus(http.StatusBadRequest)
return
}
if webhookEvent.EventType != "checkout.completed" {
c.Status(http.StatusOK)
return
}
referenceID := webhookEvent.Object.RequestId
if referenceID == "" {
referenceID = webhookEvent.Object.Metadata["reference_id"]
}
config, err := model.OrderPaymentGatewayConfiguration(model.PaymentProviderCreem, referenceID, true, true)
if err != nil || !verifyCreemSignature(string(bodyBytes), c.GetHeader(CreemSignatureHeader), config["CreemWebhookSecret"]) {
c.AbortWithStatus(http.StatusUnauthorized)
return
}
if config["CreemTestMode"] != "true" && (webhookEvent.Object.Mode == "test" || webhookEvent.Object.Order.Mode == "test") {
c.AbortWithStatus(http.StatusBadRequest)
return
}
@@ -388,14 +366,14 @@ type CreemCheckoutResponse struct {
Id string `json:"id"`
}
func genCreemLink(ctx context.Context, referenceId string, product *CreemProduct, email string, username string) (string, error) {
if setting.CreemApiKey == "" {
func genCreemLink(ctx context.Context, referenceId string, product *CreemProduct, email string, username string, config model.PaymentGatewayConfiguration) (string, error) {
if config.Values["CreemApiKey"] == "" {
return "", errors.New("Creem API key is not configured")
}
// 根据测试模式选择 API 端点
apiUrl := "https://api.creem.io/v1/checkouts"
if setting.CreemTestMode {
if config.Values["CreemTestMode"] == "true" {
apiUrl = "https://test-api.creem.io/v1/checkouts"
logger.LogInfo(ctx, common.LogText("Creem using test environment api_url=%s", apiUrl))
}
@@ -418,26 +396,27 @@ func genCreemLink(ctx context.Context, referenceId string, product *CreemProduct
}
// 序列化请求数据
jsonData, err := json.Marshal(requestData)
jsonData, err := common.Marshal(requestData)
if err != nil {
return "", fmt.Errorf("failed to marshal request data: %v", err)
}
// 创建 HTTP 请求
req, err := http.NewRequest("POST", apiUrl, bytes.NewBuffer(jsonData))
req, err := http.NewRequestWithContext(ctx, http.MethodPost, apiUrl, bytes.NewBuffer(jsonData))
if err != nil {
return "", fmt.Errorf("failed to create HTTP request: %v", err)
}
// 设置请求头
req.Header.Set("Content-Type", "application/json")
req.Header.Set("x-api-key", setting.CreemApiKey)
req.Header.Set("x-api-key", config.Values["CreemApiKey"])
logger.LogInfo(ctx, common.LogText("Creem payment request sent api_url=%s product_id=%s email=%q trade_no=%s", apiUrl, product.ProductId, email, referenceId))
// 发送请求
client := &http.Client{
Timeout: 30 * time.Second,
Timeout: 30 * time.Second,
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
}
resp, err := client.Do(req)
if err != nil {
@@ -451,15 +430,18 @@ func genCreemLink(ctx context.Context, referenceId string, product *CreemProduct
return "", fmt.Errorf("failed to read response: %v", err)
}
logger.LogInfo(ctx, common.LogText("Creem API response received trade_no=%s status_code=%d body=%q", referenceId, resp.StatusCode, string(body)))
logger.LogInfo(ctx, common.LogText("Creem API response received trade_no=%s status_code=%d", referenceId, resp.StatusCode))
// 检查响应状态
if resp.StatusCode/100 != 2 {
if resp.StatusCode == http.StatusUnauthorized {
_ = model.StopPaymentGatewayRevision(model.PaymentProviderCreem, config.RevisionID)
}
return "", fmt.Errorf("Creem API http status %d ", resp.StatusCode)
}
// 解析响应
var checkoutResp CreemCheckoutResponse
err = json.Unmarshal(body, &checkoutResp)
err = common.Unmarshal(body, &checkoutResp)
if err != nil {
return "", fmt.Errorf("failed to parse response: %v", err)
}
+1 -1
View File
@@ -314,7 +314,7 @@ func TestWalletCustomTopUpAmountPolicy(t *testing.T) {
require.NoError(t, db.AutoMigrate(&model.SystemTask{}, &model.SubscriptionPlan{}, &model.AlipayDirectSettings{}, &model.AlipayDirectMerchant{}, &model.AlipayDirectOrder{}))
const userID = 42100
require.NoError(t, db.Create(&model.User{Id: userID, Username: "custom_topup_user", Status: common.UserStatusEnabled, Group: "default"}).Error)
t.Setenv("ALIPAY_DIRECT_KEY", base64.StdEncoding.EncodeToString(make([]byte, 32)))
t.Setenv("PAYMENT_CREDENTIAL_KEY", base64.StdEncoding.EncodeToString(make([]byte, 32)))
require.NoError(t, model.SaveAlipayDirectSettings(model.AlipayDirectSettings{Enabled: true, Price: "1", MinTopUp: 1}))
require.NoError(t, db.Create(&model.AlipayDirectMerchant{AppId: "test-app", SellerId: "test-seller", Enabled: true, Mode: model.AlipayDirectModePage, RevisionId: 1}).Error)
+31 -23
View File
@@ -117,13 +117,6 @@ func (*StripeAdaptor) RequestPay(c *gin.Context, req *StripePayRequest) {
reference := fmt.Sprintf("new-api-ref-%d-%d-%s", user.Id, time.Now().UnixMilli(), randstr.String(4))
referenceId := "ref_" + common.Sha1([]byte(reference))
payLink, err := genStripeLink(referenceId, user.StripeCustomer, user.Email, req.Amount, req.SuccessURL, req.CancelURL)
if err != nil {
logger.LogError(c.Request.Context(), common.LogText("Stripe failed to create Checkout Session user_id=%d trade_no=%s amount=%d error=%q", id, referenceId, req.Amount, err.Error()))
paymentError(c, common.NewMessage("Failed to start payment"))
return
}
topUp := &model.TopUp{
UserId: id,
Amount: req.Amount,
@@ -134,10 +127,17 @@ func (*StripeAdaptor) RequestPay(c *gin.Context, req *StripePayRequest) {
CreateTime: time.Now().Unix(),
Status: common.TopUpStatusPending,
}
err = topUp.Insert()
err = topUp.InsertGatewayOrder(checkoutGateway(c).RevisionID)
if err != nil {
logger.LogError(c.Request.Context(), common.LogText("Stripe failed to create top-up order user_id=%d trade_no=%s amount=%d error=%q", id, referenceId, req.Amount, err.Error()))
paymentError(c, common.NewMessage("Failed to create order"))
paymentGatewayOrderError(c, err)
return
}
payLink, err := genStripeLink(referenceId, user.StripeCustomer, user.Email, req.Amount, req.SuccessURL, req.CancelURL, checkoutGateway(c))
if err != nil {
logger.LogError(c.Request.Context(), common.LogText("Stripe failed to create Checkout Session user_id=%d trade_no=%s amount=%d error=%q", id, referenceId, req.Amount, err.Error()))
paymentError(c, common.NewMessage("Failed to start payment"))
return
}
logger.LogInfo(c.Request.Context(), common.LogText("Stripe top-up order created user_id=%d trade_no=%s amount=%d money=%.2f", id, referenceId, req.Amount, chargedMoney))
@@ -171,12 +171,6 @@ func RequestStripePay(c *gin.Context) {
func StripeWebhook(c *gin.Context) {
ctx := c.Request.Context()
if !isStripeWebhookEnabled() {
logger.LogWarn(ctx, common.LogText("Stripe webhook rejected reason=webhook_disabled path=%q client_ip=%s", c.Request.RequestURI, c.ClientIP()))
c.AbortWithStatus(http.StatusForbidden)
return
}
payload, err := io.ReadAll(c.Request.Body)
if err != nil {
logger.LogError(ctx, common.LogText("Stripe webhook failed to read request body path=%q client_ip=%s error=%q", c.Request.RequestURI, c.ClientIP(), err.Error()))
@@ -185,8 +179,18 @@ func StripeWebhook(c *gin.Context) {
}
signature := c.GetHeader("Stripe-Signature")
logger.LogInfo(ctx, common.LogText("Stripe webhook received request path=%q client_ip=%s signature=%q body=%q", c.Request.RequestURI, c.ClientIP(), signature, string(payload)))
event, err := webhook.ConstructEventWithOptions(payload, signature, setting.StripeWebhookSecret, webhook.ConstructEventOptions{
var envelope stripe.Event
if common.Unmarshal(payload, &envelope) != nil || envelope.Data == nil {
c.AbortWithStatus(http.StatusBadRequest)
return
}
tradeNo := envelope.GetObjectValue("client_reference_id")
config, err := model.OrderPaymentGatewayConfiguration(model.PaymentProviderStripe, tradeNo, true, true)
if err != nil || config["StripeWebhookSecret"] == "" {
c.AbortWithStatus(http.StatusForbidden)
return
}
event, err := webhook.ConstructEventWithOptions(payload, signature, config["StripeWebhookSecret"], webhook.ConstructEventOptions{
IgnoreAPIVersionMismatch: true,
})
@@ -196,6 +200,10 @@ func StripeWebhook(c *gin.Context) {
return
}
if !event.Livemode && (strings.HasPrefix(config["StripeApiSecret"], "sk_live_") || strings.HasPrefix(config["StripeApiSecret"], "rk_live_")) {
c.AbortWithStatus(http.StatusBadRequest)
return
}
callerIp := c.ClientIP()
logger.LogInfo(ctx, common.LogText("Stripe webhook signature verified event_type=%s client_ip=%s path=%q", string(event.Type), callerIp, c.Request.RequestURI))
var fulfillmentErr error
@@ -370,13 +378,11 @@ func sessionExpired(ctx context.Context, event stripe.Event) {
// - cancelURL: custom URL to redirect when payment is canceled (empty for default)
//
// Returns the checkout session URL or an error if the session creation fails.
func genStripeLink(referenceId string, customerId string, email string, amount int64, successURL string, cancelURL string) (string, error) {
if !strings.HasPrefix(setting.StripeApiSecret, "sk_") && !strings.HasPrefix(setting.StripeApiSecret, "rk_") {
func genStripeLink(referenceId string, customerId string, email string, amount int64, successURL string, cancelURL string, config model.PaymentGatewayConfiguration) (string, error) {
if !strings.HasPrefix(config.Values["StripeApiSecret"], "sk_") && !strings.HasPrefix(config.Values["StripeApiSecret"], "rk_") {
return "", errors.New("invalid Stripe API key")
}
stripe.Key = setting.StripeApiSecret
// Use custom URLs if provided, otherwise use defaults
if successURL == "" {
successURL = paymentReturnPath("/usage-logs")
@@ -391,7 +397,7 @@ func genStripeLink(referenceId string, customerId string, email string, amount i
CancelURL: stripe.String(cancelURL),
LineItems: []*stripe.CheckoutSessionLineItemParams{
{
Price: stripe.String(setting.StripePriceId),
Price: stripe.String(config.Values["StripePriceId"]),
Quantity: stripe.Int64(amount),
},
},
@@ -409,7 +415,9 @@ func genStripeLink(referenceId string, customerId string, email string, amount i
params.Customer = stripe.String(customerId)
}
result, err := session.New(params)
client := session.Client{B: stripe.GetBackend(stripe.APIBackend), Key: config.Values["StripeApiSecret"]}
result, err := client.New(params)
stopRejectedPaymentGateway(model.PaymentProviderStripe, config.RevisionID, err)
if err != nil {
return "", err
}
+41 -38
View File
@@ -23,24 +23,24 @@ import (
"github.com/waffo-com/waffo-go/types/order"
)
func getWaffoSDK() (*waffo.Waffo, error) {
func waffoSDKForConfig(values map[string]string) (*waffo.Waffo, error) {
env := config.Sandbox
apiKey := setting.WaffoSandboxApiKey
privateKey := setting.WaffoSandboxPrivateKey
publicKey := setting.WaffoSandboxPublicCert
if !setting.WaffoSandbox {
apiKey := values["WaffoSandboxApiKey"]
privateKey := values["WaffoSandboxPrivateKey"]
publicKey := values["WaffoSandboxPublicCert"]
if values["WaffoSandbox"] != "true" {
env = config.Production
apiKey = setting.WaffoApiKey
privateKey = setting.WaffoPrivateKey
publicKey = setting.WaffoPublicCert
apiKey = values["WaffoApiKey"]
privateKey = values["WaffoPrivateKey"]
publicKey = values["WaffoPublicCert"]
}
builder := config.NewConfigBuilder().
APIKey(apiKey).
PrivateKey(privateKey).
WaffoPublicKey(publicKey).
Environment(env)
if setting.WaffoMerchantId != "" {
builder = builder.MerchantID(setting.WaffoMerchantId)
if values["WaffoMerchantId"] != "" {
builder = builder.MerchantID(values["WaffoMerchantId"])
}
cfg, err := builder.Build()
if err != nil {
@@ -145,11 +145,7 @@ func RequestWaffoAmount(c *gin.Context) {
// RequestWaffoPay 创建 Waffo 支付订单
func RequestWaffoPay(c *gin.Context) {
if !setting.WaffoEnabled {
paymentError(c, common.NewMessage("Waffo payment is not enabled"))
return
}
values := checkoutGateway(c).Values
var req WaffoPayRequest
if err := c.ShouldBindJSON(&req); err != nil {
paymentError(c, common.NewMessage("Invalid parameters"))
@@ -231,13 +227,13 @@ func RequestWaffoPay(c *gin.Context) {
CreateTime: time.Now().Unix(),
Status: common.TopUpStatusPending,
}
if err := topUp.Insert(); err != nil {
if err := topUp.InsertGatewayOrder(checkoutGateway(c).RevisionID); err != nil {
logger.LogError(c.Request.Context(), common.LogText("Waffo failed to create top-up order user_id=%d trade_no=%s amount=%d error=%q", id, merchantOrderId, req.Amount, err.Error()))
paymentError(c, common.NewMessage("Failed to create order"))
paymentGatewayOrderError(c, err)
return
}
sdk, err := getWaffoSDK()
sdk, err := waffoSDKForConfig(values)
if err != nil {
logger.LogError(c.Request.Context(), common.LogText("Waffo SDK initialization failed user_id=%d trade_no=%s error=%q", id, merchantOrderId, err.Error()))
topUp.Status = common.TopUpStatusFailed
@@ -248,12 +244,12 @@ func RequestWaffoPay(c *gin.Context) {
callbackAddr := service.GetCallbackAddress()
notifyUrl := callbackAddr + "/api/waffo/webhook"
if setting.WaffoNotifyUrl != "" {
notifyUrl = setting.WaffoNotifyUrl
if values["WaffoNotifyUrl"] != "" {
notifyUrl = values["WaffoNotifyUrl"]
}
returnUrl := paymentReturnPath("/wallet?show_history=true")
if setting.WaffoReturnUrl != "" {
returnUrl = setting.WaffoReturnUrl
if values["WaffoReturnUrl"] != "" {
returnUrl = values["WaffoReturnUrl"]
}
currency := getWaffoCurrency()
@@ -267,7 +263,7 @@ func RequestWaffoPay(c *gin.Context) {
OrderRequestedAt: time.Now().UTC().Format("2006-01-02T15:04:05.000Z"),
NotifyURL: notifyUrl,
MerchantInfo: &order.MerchantInfo{
MerchantID: setting.WaffoMerchantId,
MerchantID: values["WaffoMerchantId"],
},
UserInfo: &order.UserInfo{
UserID: strconv.Itoa(user.Id),
@@ -292,7 +288,11 @@ func RequestWaffoPay(c *gin.Context) {
return
}
if !resp.IsSuccess() {
logger.LogWarn(c.Request.Context(), common.LogText("Waffo order creation rejected user_id=%d trade_no=%s code=%s message=%q response=%q", id, merchantOrderId, resp.Code, resp.Message, common.GetJsonString(resp)))
switch resp.Code {
case "A0001", "A0002", "A0004", "A0006", "C0002":
_ = model.StopPaymentGatewayRevision(model.PaymentProviderWaffo, checkoutGateway(c).RevisionID)
}
logger.LogWarn(c.Request.Context(), common.LogText("Waffo order creation rejected user_id=%d trade_no=%s code=%s", id, merchantOrderId, resp.Code))
topUp.Status = common.TopUpStatusFailed
_ = topUp.Update()
paymentError(c, common.NewMessage("Failed to start payment"))
@@ -334,12 +334,6 @@ type webhookSubscriptionInfo struct {
// WaffoWebhook 处理 Waffo 回调通知(支付/退款/订阅)
func WaffoWebhook(c *gin.Context) {
if !isWaffoWebhookEnabled() {
logger.LogWarn(c.Request.Context(), common.LogText("Waffo webhook rejected reason=webhook_disabled path=%q client_ip=%s", c.Request.RequestURI, c.ClientIP()))
c.AbortWithStatus(http.StatusForbidden)
return
}
bodyBytes, err := io.ReadAll(c.Request.Body)
if err != nil {
logger.LogError(c.Request.Context(), common.LogText("Waffo webhook failed to read request body path=%q client_ip=%s error=%q", c.Request.RequestURI, c.ClientIP(), err.Error()))
@@ -347,7 +341,17 @@ func WaffoWebhook(c *gin.Context) {
return
}
sdk, err := getWaffoSDK()
var candidate webhookPayloadWithSubInfo
if common.Unmarshal(bodyBytes, &candidate) != nil {
c.AbortWithStatus(http.StatusBadRequest)
return
}
values, err := model.OrderPaymentGatewayConfiguration(model.PaymentProviderWaffo, candidate.Result.MerchantOrderID, true, false)
if err != nil {
c.AbortWithStatus(http.StatusForbidden)
return
}
sdk, err := waffoSDKForConfig(values)
if err != nil {
logger.LogError(c.Request.Context(), common.LogText("Waffo webhook SDK initialization failed path=%q client_ip=%s error=%q", c.Request.RequestURI, c.ClientIP(), err.Error()))
c.AbortWithStatus(http.StatusInternalServerError)
@@ -357,18 +361,17 @@ func WaffoWebhook(c *gin.Context) {
wh := sdk.Webhook()
bodyStr := string(bodyBytes)
signature := c.GetHeader("X-SIGNATURE")
logger.LogInfo(c.Request.Context(), common.LogText("Waffo webhook received request path=%q client_ip=%s signature=%q body=%q", c.Request.RequestURI, c.ClientIP(), signature, bodyStr))
// 验证请求签名
if !wh.VerifySignature(bodyStr, signature) {
logger.LogWarn(c.Request.Context(), common.LogText("Waffo webhook signature verification failed path=%q client_ip=%s signature=%q body=%q", c.Request.RequestURI, c.ClientIP(), signature, bodyStr))
logger.LogWarn(c.Request.Context(), common.LogText("Waffo webhook signature verification failed path=%q client_ip=%s", c.Request.URL.Path, c.ClientIP()))
c.AbortWithStatus(http.StatusBadRequest)
return
}
var event core.WebhookEvent
if err := common.Unmarshal(bodyBytes, &event); err != nil {
logger.LogError(c.Request.Context(), common.LogText("Waffo webhook failed to parse path=%q client_ip=%s error=%q body=%q", c.Request.RequestURI, c.ClientIP(), err.Error(), bodyStr))
logger.LogError(c.Request.Context(), common.LogText("Waffo webhook failed to parse path=%q client_ip=%s", c.Request.URL.Path, c.ClientIP()))
sendWaffoWebhookResponse(c, wh, false, "invalid payload")
return
}
@@ -378,12 +381,12 @@ func WaffoWebhook(c *gin.Context) {
// 解析为扩展类型,区分普通支付和订阅支付
var payload webhookPayloadWithSubInfo
if err := common.Unmarshal(bodyBytes, &payload); err != nil {
logger.LogError(c.Request.Context(), common.LogText("Waffo failed to parse payment callback payload event_type=%s client_ip=%s error=%q body=%q", event.EventType, c.ClientIP(), err.Error(), bodyStr))
logger.LogError(c.Request.Context(), common.LogText("Waffo failed to parse payment callback payload event_type=%s client_ip=%s", event.EventType, c.ClientIP()))
sendWaffoWebhookResponse(c, wh, false, "invalid payment payload")
return
}
logger.LogInfo(c.Request.Context(), common.LogText("Waffo webhook verified and parsed event_type=%s merchant_order_id=%s order_status=%s client_ip=%s", event.EventType, payload.Result.MerchantOrderID, payload.Result.OrderStatus, c.ClientIP()))
handleWaffoPayment(c, wh, &payload.Result.PaymentNotificationResult)
handleWaffoPayment(c, wh, &payload.Result.PaymentNotificationResult, values["WaffoMerchantId"])
default:
logger.LogInfo(c.Request.Context(), common.LogText("Waffo webhook ignored event event_type=%s client_ip=%s", event.EventType, c.ClientIP()))
sendWaffoWebhookResponse(c, wh, true, "")
@@ -391,13 +394,13 @@ func WaffoWebhook(c *gin.Context) {
}
// handleWaffoPayment 处理支付完成通知
func handleWaffoPayment(c *gin.Context, wh *core.WebhookHandler, result *core.PaymentNotificationResult) {
func handleWaffoPayment(c *gin.Context, wh *core.WebhookHandler, result *core.PaymentNotificationResult, expectedMerchant string) {
// Our checkout uses the same ID for paymentRequestId and merchantOrderId.
// Reject explicit conflicts before any status change; these SDK fields are
// optional, so absent metadata does not change existing callback behavior.
merchantID, hasMerchantID := result.MerchantInfo["merchantId"]
if (result.PaymentRequestID != "" && result.PaymentRequestID != result.MerchantOrderID) ||
(hasMerchantID && setting.WaffoMerchantId != "" && merchantID != setting.WaffoMerchantId) {
(hasMerchantID && expectedMerchant != "" && merchantID != expectedMerchant) {
logger.LogError(c.Request.Context(), common.LogText("Waffo top-up processing failed trade_no=%s client_ip=%s error=%q", result.MerchantOrderID, c.ClientIP(), "payment order mismatch"))
sendWaffoWebhookResponse(c, wh, false, "payment order mismatch")
return
+14 -17
View File
@@ -340,10 +340,7 @@ func getWaffoPancakeBuyerIdentity(user *model.User) string {
}
func RequestWaffoPancakePay(c *gin.Context) {
if !isWaffoPancakeTopUpEnabled() {
paymentError(c, common.NewMessage("Waffo Pancake configuration is incomplete"))
return
}
config := checkoutGateway(c)
var req WaffoPancakePayRequest
if err := c.ShouldBindJSON(&req); err != nil {
@@ -388,15 +385,15 @@ func RequestWaffoPancakePay(c *gin.Context) {
CreateTime: time.Now().Unix(),
Status: common.TopUpStatusPending,
}
if err := topUp.Insert(); err != nil {
if err := topUp.InsertGatewayOrder(checkoutGateway(c).RevisionID); err != nil {
logger.LogError(c.Request.Context(), common.LogText("Waffo Pancake failed to create top-up order user_id=%d trade_no=%s amount=%d error=%q", id, tradeNo, req.Amount, err.Error()))
paymentError(c, common.NewMessage("Failed to create order"))
paymentGatewayOrderError(c, err)
return
}
expiresInSeconds := 45 * 60
session, err := service.CreateWaffoPancakeCheckoutSession(c.Request.Context(), &service.WaffoPancakeCreateSessionParams{
ProductID: setting.WaffoPancakeProductID,
ProductID: config.Values["WaffoPancakeProductID"],
BuyerIdentity: getWaffoPancakeBuyerIdentity(user),
PriceSnapshot: &service.WaffoPancakePriceSnapshot{
Amount: formatWaffoPancakeAmount(payMoney),
@@ -405,7 +402,8 @@ func RequestWaffoPancakePay(c *gin.Context) {
BuyerEmail: getWaffoPancakeBuyerEmail(user),
ExpiresInSeconds: &expiresInSeconds,
OrderMerchantExternalID: tradeNo,
})
}, config.Values["WaffoPancakeMerchantID"], config.Values["WaffoPancakePrivateKey"])
stopRejectedPaymentGateway(model.PaymentProviderWaffoPancake, config.RevisionID, err)
if err != nil {
logger.LogError(c.Request.Context(), common.LogText("Waffo Pancake failed to create checkout session user_id=%d trade_no=%s error=%q", id, tradeNo, err.Error()))
topUp.Status = common.TopUpStatusFailed
@@ -429,12 +427,6 @@ func RequestWaffoPancakePay(c *gin.Context) {
}
func WaffoPancakeWebhook(c *gin.Context) {
if !isWaffoPancakeWebhookEnabled() {
logger.LogWarn(c.Request.Context(), common.LogText("Waffo Pancake webhook rejected reason=webhook_disabled path=%q client_ip=%s", c.Request.RequestURI, c.ClientIP()))
c.String(http.StatusForbidden, "webhook disabled")
return
}
// :env splits test vs prod traffic at the routing layer — operator
// registers each URL in the matching webhook slot in Pancake's dashboard.
// We then enforce event.mode == expectedEnv to catch mis-registrations.
@@ -456,11 +448,10 @@ func WaffoPancakeWebhook(c *gin.Context) {
}
signature := c.GetHeader("X-Waffo-Signature")
logger.LogInfo(c.Request.Context(), common.LogText("Waffo Pancake webhook received request path=%q client_ip=%s signature=%q body=%q", c.Request.RequestURI, c.ClientIP(), signature, string(bodyBytes)))
event, err := service.VerifyConfiguredWaffoPancakeWebhook(string(bodyBytes), signature)
event, err := service.VerifyWaffoPancakeWebhook(string(bodyBytes), signature)
if err != nil {
logger.LogWarn(c.Request.Context(), common.LogText("Waffo Pancake webhook signature verification failed path=%q client_ip=%s signature=%q body=%q error=%q", c.Request.RequestURI, c.ClientIP(), signature, string(bodyBytes), err.Error()))
logger.LogWarn(c.Request.Context(), common.LogText("Waffo Pancake webhook signature verification failed path=%q client_ip=%s", c.Request.URL.Path, c.ClientIP()))
c.String(http.StatusUnauthorized, "invalid signature")
return
}
@@ -485,6 +476,12 @@ func WaffoPancakeWebhook(c *gin.Context) {
rawTradeNo := strings.TrimSpace(event.Data.OrderMerchantExternalID)
isSubscription := strings.HasPrefix(rawTradeNo, "WAFFO_PANCAKE_SUB-")
values, err := model.OrderPaymentGatewayConfiguration(model.PaymentProviderWaffoPancake, rawTradeNo, !isSubscription, isSubscription)
if err != nil || values["WaffoPancakeStoreID"] == "" || event.StoreID != values["WaffoPancakeStoreID"] || expectedEnv != "prod" {
c.String(http.StatusForbidden, "order environment or store mismatch")
return
}
// The SDK distinguishes display amount from the optional after-tax total.
// Only an explicit total proves the receipt amount; never add tax or infer
// a missing total from the checkout price.
+6 -6
View File
@@ -31,12 +31,12 @@ services:
- REDIS_CONN_STRING=redis://redis
- TZ=Asia/Shanghai
- BATCH_UPDATE_ENABLED=true
# 上游监控凭据加密:首次配置运行 openssl rand -base64 32 生成密钥,再取消下一行注释并替换占位值。
# Upstream credential encryption: generate with openssl rand -base64 32, then uncomment and replace the placeholder.
# - UPSTREAM_MONITOR_KEY=base64_encoded_32_random_bytes
# 修改后执行 / Apply with: docker compose -f docker-compose.dev.yml up -d --no-deps --force-recreate new-api
# 单纯重启不会更新环境变量。密钥独立备份,所有节点使用同一持久密钥;已有凭据时沿用原密钥。
# A restart does not reload environment changes. Back up the key separately; reuse the same persistent key on all nodes and for existing credentials.
# 从 .env 注入需要跨重启保留的密钥。更新后执行:
# docker compose --env-file .env -f docker-compose.dev.yml up -d --no-deps --force-recreate new-api
- "SESSION_SECRET=${SESSION_SECRET:-}"
- "CRYPTO_SECRET=${CRYPTO_SECRET:-}"
- "UPSTREAM_MONITOR_KEY=${UPSTREAM_MONITOR_KEY:-}"
- "PAYMENT_CREDENTIAL_KEY=${PAYMENT_CREDENTIAL_KEY:-}"
# Local HTTP dev mode: keep Secure=false and leave TRUSTED_URL unset. This disables the refresh/logout OriginGuard so the :5173 -> :3000 dev proxy works.
- SESSION_COOKIE_SECURE=false
# For HTTPS only: set Secure=true and list every exact trusted HTTPS browser Origin. This does not configure relay CORS.
+19 -15
View File
@@ -5,10 +5,10 @@
# 2. Access at http://localhost:3000
#
# Using MySQL instead of PostgreSQL:
# 1. Comment out the postgres service and SQL_DSN line 15
# 2. Uncomment the mysql service and SQL_DSN line 16
# 3. Uncomment mysql in depends_on (line 28)
# 4. Uncomment mysql_data in volumes section (line 64)
# 1. Comment out the postgres service and its SQL_DSN.
# 2. Uncomment the mysql service and its SQL_DSN.
# 3. Replace postgres with mysql in new-api's depends_on.
# 4. Uncomment mysql_data in the top-level volumes section.
#
# ⚠️ IMPORTANT: Change all default passwords before deploying to production!
@@ -16,6 +16,7 @@ version: '3.4' # For compatibility with older Docker versions
services:
new-api:
# 使用 NovaLink 专属功能时,先按 README 构建 novalink-new-api:local,再将 image 改为该镜像。
image: calciumion/new-api:latest
container_name: new-api
restart: always
@@ -35,20 +36,23 @@ services:
- TZ=Asia/Shanghai
- ERROR_LOG_ENABLED=true # 是否启用错误日志记录 (Whether to enable error log recording)
- BATCH_UPDATE_ENABLED=true # 是否启用批量更新 (Whether to enable batch update)
- NODE_NAME=new-api-node-1 # 节点名称,用于审计日志中标识节点身份;多节点/容器部署时建议设置 (Node name used in audit logs; recommended when running multiple instances or in containers)
- "NODE_NAME=${NODE_NAME:-new-api-node-1}" # 节点名称用于审计,多节点分别设置唯一名称
- "NODE_TYPE=${NODE_TYPE:-master}" # 多节点部署只保留一个 master,其余为 slave
# - DEFAULT_LANGUAGE=zh-CN # 默认语言:日志输出,以及对方没有指定语言时返回的提示、邮件和通知;可选 en、zh-CN、zh-TW,不设置为 en (Default language of logs and of messages, emails and notifications when the reader states none: en, zh-CN or zh-TW; en if unset)
# - STREAMING_TIMEOUT=300 # 流模式无响应超时时间,单位秒,默认120秒,如果出现空补全可以尝试改为更大值 (Streaming timeout in seconds, default is 120s. Increase if experiencing empty completions)
# - RELAY_IDLE_CONN_TIMEOUT=90 # Relay HTTP 客户端空闲连接超时时间,单位秒,默认跟随 Go 标准库,设置为0表示不限制 (Relay HTTP client idle keep-alive timeout in seconds, defaults to Go standard library; set 0 to disable)
# - SESSION_SECRET=random_string # 多机部署时设置,必须修改这个随机字符串!! (multi-node deployment, set this to a random string!!!!!!!)
# 上游监控凭据加密:首次配置运行 openssl rand -base64 32 生成密钥,再取消下一行注释并替换占位值。
# Upstream credential encryption: generate with openssl rand -base64 32, then uncomment and replace the placeholder.
# - UPSTREAM_MONITOR_KEY=base64_encoded_32_random_bytes
# 修改后执行 / Apply with: docker compose up -d --no-deps --force-recreate new-api
# 单纯重启不会更新环境变量。密钥独立备份,所有节点使用同一持久密钥;已有凭据时沿用原密钥。
# A restart does not reload environment changes. Back up the key separately; reuse the same persistent key on all nodes and for existing credentials.
# - SESSION_COOKIE_SECURE=true # true:启用 Secure Refresh Cookie 和严格 refresh/logout OriginGuard;false/未配置:关闭 OriginGuard,仅用于本地 HTTP (true: Secure cookie + strict refresh/logout OriginGuard; false/unset: guard disabled for local HTTP only)
# - SESSION_COOKIE_TRUSTED_URL=https://example.com,https://admin.example.com # Secure=true 时必填的精确 HTTPS Origin;不是 relay CORS 白名单,不支持通配符/路径 (Required exact HTTPS origins when Secure=true; not a relay CORS allowlist, no wildcard/path)
# - TRUSTED_PROXIES=172.20.0.0/16 # 未配置时信任回环/RFC1918/fc00::/7 并告警,none 为严格模式,显式列表替代默认值 (Unset trusts loopback/RFC 1918/fc00::/7 with a warning; none trusts no proxies; an explicit list replaces defaults)
# 在同目录 .env 中配置(详见 .env.example 和 README)。修改后重建 new-api 容器,restart 不会刷新变量。
# 生产环境设置固定的随机 SESSION_SECRET。CRYPTO_SECRET 留空时沿用 SESSION_SECRET。
- "SESSION_SECRET=${SESSION_SECRET:-}"
- "CRYPTO_SECRET=${CRYPTO_SECRET:-}"
# 按功能启用,首次各自运行 openssl rand -base64 32。已有凭据时沿用原值,密钥与数据库分开备份。
- "UPSTREAM_MONITOR_KEY=${UPSTREAM_MONITOR_KEY:-}"
- "PAYMENT_CREDENTIAL_KEY=${PAYMENT_CREDENTIAL_KEY:-}"
# 公网 HTTPS 同时设置 true 和精确的 HTTPS Origin 列表。仅本地 HTTP 开发留空或用 false,且不填 Origin。
- "SESSION_COOKIE_SECURE=${SESSION_COOKIE_SECURE:-false}"
- "SESSION_COOKIE_TRUSTED_URL=${SESSION_COOKIE_TRUSTED_URL:-}"
# 填可信反代的 IP/CIDR,直连可设 none。留空沿用程序默认的回环及常见私网信任范围。
- "TRUSTED_PROXIES=${TRUSTED_PROXIES:-}"
# - USER_SESSION_ACTIVE_LIMIT=50
# - USER_SESSION_ISSUANCE_LIMIT=100
# - USER_SESSION_ISSUANCE_WINDOW_SECONDS=86400 # 不得大于 revoked 保留期 (must not exceed revoked retention)
+5
View File
@@ -369,6 +369,11 @@ func InitResources() error {
common.FatalLog(common.LogText("failed to initialize database: %s", err.Error()))
return err
}
if !common.IsMasterNode {
if err = model.VerifyPaymentCredentialStorage(); err != nil {
return fmt.Errorf("verify payment credential storage: %w", err)
}
}
if err = model.InitWalletAccounting(); err != nil {
return fmt.Errorf("initialize wallet accounting: %w", err)
}
+3
View File
@@ -225,6 +225,9 @@ var accessTokenRouteRules = map[string]accessTokenRouteRule{
"PATCH /api/option/model_pricing": accessTokenScopeRule("option:write"),
"POST /api/option/model_pricing/convert": accessTokenScopeRule("option:read"),
"POST /api/option/model_pricing/preview": accessTokenScopeRule("option:read"),
"GET /api/option/payment-gateways": accessTokenSessionRule,
"PUT /api/option/payment-gateways/:gateway": accessTokenSessionRule,
"DELETE /api/option/payment-gateways/:gateway": accessTokenSessionRule,
"POST /api/option/payment_compliance": accessTokenSessionRule,
"GET /api/option/alipay-direct": accessTokenSessionRule,
"PUT /api/option/alipay-direct": accessTokenSessionRule,
+3 -2
View File
@@ -39,10 +39,11 @@ func Distribute() func(c *gin.Context) {
service.RecordRequestPolicyTermination(c, types.NewErrorWithStatusCode(errors.New("request rejected"), types.ErrorCodeInvalidRequest, c.Writer.Status(), types.ErrOptionWithSkipRetry()))
}
}()
requestPath := common.NormalizeRelayPath(c.Request.URL.Path)
constraints := service.GetChannelConstraints(c)
constraints.AddFilter(taskdto.ChannelFilter{
Kind: taskdto.FilterRequestPath,
RequestPath: c.Request.URL.Path,
RequestPath: requestPath,
})
service.AppendTaskPluginIdentityFilter(c, c.GetString("expected_task_plugin_key"))
modelRequest, shouldSelectChannel, err := getModelRequest(c)
@@ -112,7 +113,7 @@ func Distribute() func(c *gin.Context) {
Ctx: c,
ModelName: modelRequest.Model,
TokenGroup: usingGroup,
RequestPath: c.Request.URL.Path,
RequestPath: requestPath,
Retry: common.GetPointer(0),
})
}
+20
View File
@@ -36,8 +36,20 @@ end
return {1, count, ttl}
`
// statusClientClosedRequest is the nginx convention for a request the client
// abandoned before the server responded. It is never seen by the client and
// only keeps access logs from counting the abort as a server error.
const statusClientClosedRequest = 499
var inMemoryRateLimiter common.InMemoryRateLimiter
// requestCanceledByClient reports whether a Redis rate limit failure was caused
// by the client closing its request. A deadline or any other Redis failure is
// still a server error, so the limiter keeps failing closed for those.
func requestCanceledByClient(c *gin.Context, err error) bool {
return errors.Is(err, context.Canceled) && errors.Is(c.Request.Context().Err(), context.Canceled)
}
var defNext = func(c *gin.Context) {
c.Next()
}
@@ -115,6 +127,10 @@ func redisRateLimiter(c *gin.Context, maxRequestNum int, duration int64, mark st
duration,
)
if err != nil {
if requestCanceledByClient(c, err) {
c.AbortWithStatus(statusClientClosedRequest)
return
}
logger.LogError(c.Request.Context(), common.LogText("rate limit check failed (mark=%s): %v", mark, err))
c.Status(http.StatusInternalServerError)
c.Abort()
@@ -250,6 +266,10 @@ func userRateLimitFactory(maxRequestNum int, duration int64, mark string) func(c
func userRedisRateLimiter(c *gin.Context, maxRequestNum int, duration int64, key string) {
allowed, _, ttlSeconds, err := redisFixedWindowTake(c.Request.Context(), key, maxRequestNum, duration)
if err != nil {
if requestCanceledByClient(c, err) {
c.AbortWithStatus(statusClientClosedRequest)
return
}
logger.LogError(c.Request.Context(), common.LogText("rate limit check failed (key=%s): %v", key, err))
c.Status(http.StatusInternalServerError)
c.Abort()
+66
View File
@@ -1,11 +1,13 @@
package middleware
import (
"bytes"
"context"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"testing"
@@ -227,6 +229,70 @@ func TestRedisFailurePolicies(t *testing.T) {
assert.Equal(t, http.StatusNoContent, performRateLimitRequest(router, "/email", "192.0.2.62:12345").Code)
}
func TestRedisRateLimiterRequestContextErrors(t *testing.T) {
useRateLimitMiniRedis(t)
canceledContext := func() context.Context {
ctx, cancel := context.WithCancel(context.Background())
cancel()
return ctx
}
expiredContext := func() context.Context {
ctx, cancel := context.WithDeadline(context.Background(), time.Unix(0, 0))
cancel()
return ctx
}
tests := []struct {
name string
path string
requestCtx func() context.Context
wantStatus int
wantLogged bool
}{
{name: "IP limiter client canceled", path: "/ip", requestCtx: canceledContext, wantStatus: 499},
{name: "user limiter client canceled", path: "/user", requestCtx: canceledContext, wantStatus: 499},
{name: "IP limiter deadline exceeded", path: "/ip", requestCtx: expiredContext, wantStatus: http.StatusInternalServerError, wantLogged: true},
{name: "user limiter deadline exceeded", path: "/user", requestCtx: expiredContext, wantStatus: http.StatusInternalServerError, wantLogged: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var logs bytes.Buffer
common.LogWriterMu.Lock()
previousErrorWriter := gin.DefaultErrorWriter
gin.DefaultErrorWriter = &logs
common.LogWriterMu.Unlock()
restoreErrorWriter := func() {
common.LogWriterMu.Lock()
gin.DefaultErrorWriter = previousErrorWriter
common.LogWriterMu.Unlock()
}
t.Cleanup(restoreErrorWriter)
downstreamCalled := false
downstream := func(c *gin.Context) {
downstreamCalled = true
c.Status(http.StatusNoContent)
}
router := gin.New()
require.NoError(t, router.SetTrustedProxies(nil))
router.GET("/ip", rateLimitFactory(1, 30, "CTX-IP"), downstream)
router.GET("/user", func(c *gin.Context) { c.Set("id", 9) }, userRateLimitFactory(1, 30, "CTX-USER"), downstream)
recorder := httptest.NewRecorder()
request := httptest.NewRequestWithContext(tt.requestCtx(), http.MethodGet, tt.path, nil)
request.RemoteAddr = "192.0.2.63:12345"
router.ServeHTTP(recorder, request)
restoreErrorWriter()
assert.Equal(t, tt.wantStatus, recorder.Code)
assert.Empty(t, recorder.Body.String())
assert.False(t, downstreamCalled)
assert.Equal(t, tt.wantLogged, strings.Contains(logs.String(), "rate limit check failed"), logs.String())
})
}
}
func TestGlobalWebRateLimitCountsFrontendFilesInStaticBucket(t *testing.T) {
gin.SetMode(gin.TestMode)
previousWebEnable, previousWebNum, previousWebDuration := common.GlobalWebRateLimitEnable, common.GlobalWebRateLimitNum, common.GlobalWebRateLimitDuration
+33 -47
View File
@@ -1,13 +1,9 @@
package model
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"os"
"strings"
"time"
@@ -29,7 +25,6 @@ const (
)
var (
ErrAlipayDirectKey = common.NewMessage("ALIPAY_DIRECT_KEY must be a base64-encoded 32-byte key")
ErrAlipayDirectUnavailable = common.NewMessage("No Alipay merchant is available for this order")
ErrAlipayDirectConflict = common.NewMessage("Alipay order conflicts with an existing request")
ErrAlipayDirectInvalidOrder = common.NewMessage("Invalid Alipay order")
@@ -71,8 +66,8 @@ func SaveAlipayDirectSettings(in AlipayDirectSettings) error {
if err != nil || price.Exponent() < -8 || price.Exponent() > 8 || !price.IsPositive() || price.GreaterThan(decimal.NewFromInt(maxAlipayDirectFen)) {
return common.NewMessage("Invalid Alipay checkout settings")
}
if in.Enabled && !AlipayDirectKeyConfigured() {
return ErrAlipayDirectKey
if in.Enabled && !PaymentCredentialKeyConfigured() {
return ErrPaymentCredentialKey
}
columns := []string{"enabled", "price", "min_top_up"}
if in.QueryDelayMinutes != 0 {
@@ -136,47 +131,38 @@ type alipayDirectKeys struct {
}
func alipayDirectCipher() (cipher.AEAD, error) {
key, err := base64.StdEncoding.DecodeString(os.Getenv("ALIPAY_DIRECT_KEY"))
if err != nil || len(key) != 32 {
return nil, ErrAlipayDirectKey
}
block, err := aes.NewCipher(key)
root, err := paymentCredentialRootKey()
if err != nil {
return nil, ErrAlipayDirectKey
return nil, err
}
return cipher.NewGCM(block)
}
func AlipayDirectKeyConfigured() bool {
_, err := alipayDirectCipher()
return err == nil
return paymentCredentialCipher(root, paymentCredentialAlipayPurpose)
}
func (r AlipayDirectCredentials) encryptionContext() []byte {
return fmt.Appendf(nil, "alipay-direct-v1:%d:%d:%t:%s:%s", r.Id, r.MerchantId, r.Sandbox, r.AppId, r.SellerId)
return fmt.Appendf(nil, "alipay-direct-v2:%d:%d:%t:%s:%s", r.Id, r.MerchantId, r.Sandbox, r.AppId, r.SellerId)
}
func (r AlipayDirectCredentials) openKeys(aead cipher.AEAD) (alipayDirectKeys, error) {
var keys alipayDirectKeys
plain, err := openPaymentCredential(aead, paymentCredentialAlipayPrefix, r.EncryptedKeys, r.encryptionContext())
if err != nil {
return keys, err
}
if err := common.Unmarshal(plain, &keys); err != nil || keys.PrivateKey == "" || keys.AlipayPublicKey == "" {
return alipayDirectKeys{}, errPaymentCredentialData
}
return keys, nil
}
func (r *AlipayDirectCredentials) decrypt() error {
r.PrivateKey, r.AlipayPublicKey = "", ""
aead, err := alipayDirectCipher()
if err != nil {
return err
}
secretErr := errors.New("unable to decrypt Alipay credential revision")
data, ok := strings.CutPrefix(r.EncryptedKeys, "v1:")
if !ok {
return secretErr
}
sealed, err := base64.StdEncoding.DecodeString(data)
if err != nil || len(sealed) < aead.NonceSize()+aead.Overhead() {
return secretErr
}
plain, err := aead.Open(nil, sealed[:aead.NonceSize()], sealed[aead.NonceSize():], r.encryptionContext())
keys, err := r.openKeys(aead)
if err != nil {
return secretErr
}
var keys alipayDirectKeys
if err = common.Unmarshal(plain, &keys); err != nil || keys.PrivateKey == "" || keys.AlipayPublicKey == "" {
return secretErr
return err
}
r.PrivateKey, r.AlipayPublicKey = keys.PrivateKey, keys.AlipayPublicKey
return nil
@@ -187,8 +173,11 @@ func GetAlipayDirectCredentials(revisionId int) (*AlipayDirectCredentials, error
return nil, gorm.ErrRecordNotFound
}
var rev AlipayDirectCredentials
if err := DB.Take(&rev, revisionId).Error; err != nil {
return nil, err
if err := paymentCredentialDB(DB).Take(&rev, revisionId).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, err
}
return nil, errPaymentCredentialStore
}
if err := rev.decrypt(); err != nil {
return nil, err
@@ -345,20 +334,17 @@ func SaveAlipayDirectMerchant(id int, in AlipayDirectMerchantInput) (*AlipayDire
return err
}
rev := AlipayDirectCredentials{MerchantId: merchant.Id, AppId: merchant.AppId, SellerId: merchant.SellerId, Sandbox: merchant.Sandbox}
if err = tx.Create(&rev).Error; err != nil {
return err
credentialDB := paymentCredentialDB(tx)
if err = credentialDB.Create(&rev).Error; err != nil {
return errPaymentCredentialStore
}
clear, err := common.Marshal(keys)
if err != nil {
return err
return errPaymentCredentialData
}
nonce := make([]byte, aead.NonceSize())
if _, err := rand.Read(nonce); err != nil {
return err
}
rev.EncryptedKeys = "v1:" + base64.StdEncoding.EncodeToString(aead.Seal(nonce, nonce, clear, rev.encryptionContext()))
if err = tx.Model(&rev).Update("encrypted_keys", rev.EncryptedKeys).Error; err != nil {
return err
rev.EncryptedKeys = sealPaymentCredential(aead, paymentCredentialAlipayPrefix, rev.encryptionContext(), clear)
if err = credentialDB.Model(&rev).Update("encrypted_keys", rev.EncryptedKeys).Error; err != nil {
return errPaymentCredentialStore
}
merchant.RevisionId = rev.Id
}
+2 -2
View File
@@ -177,8 +177,8 @@ func ReserveAlipayDirectOrder(in AlipayDirectOrderInput) (*AlipayDirectOrder, er
return ErrAlipayDirectConflict
}
}
if !AlipayDirectKeyConfigured() {
return ErrAlipayDirectKey
if !PaymentCredentialKeyConfigured() {
return ErrPaymentCredentialKey
}
now := common.GetTimestamp()
if in.AmountFen < 1 || in.AmountFen > maxAlipayDirectFen || in.ExpiresAt <= now || in.ExpiresAt > now+86400 {
+229 -1
View File
@@ -1,15 +1,19 @@
package model
import (
"bytes"
"encoding/base64"
"fmt"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/setting/operation_setting"
mysqlDriver "github.com/go-sql-driver/mysql"
"github.com/shopspring/decimal"
"github.com/stretchr/testify/assert"
@@ -18,6 +22,230 @@ import (
gormlogger "gorm.io/gorm/logger"
)
func TestPaymentCredentialMigration(t *testing.T) {
for _, dialect := range []string{"sqlite", "mysql", "postgres"} {
t.Run(dialect, func(t *testing.T) {
verifyPaymentCredentialMigration(t, dialect)
})
}
}
func verifyPaymentCredentialMigration(t *testing.T, dialect string) {
dsn := "local"
oldPath := common.SQLitePath
switch dialect {
case "mysql":
dsn = os.Getenv("TEST_PAYMENT_CREDENTIAL_MYSQL_DSN")
if dsn == "" {
t.Skip("dedicated TEST_PAYMENT_CREDENTIAL_MYSQL_DSN is not configured")
}
config, err := mysqlDriver.ParseDSN(dsn)
require.NoError(t, err)
require.Equal(t, "payment_credential_verify", config.DBName)
require.Contains(t, []string{"127.0.0.1", "localhost"}, strings.Split(config.Addr, ":")[0])
case "postgres":
dsn = os.Getenv("TEST_PAYMENT_CREDENTIAL_POSTGRES_DSN")
if dsn == "" {
t.Skip("dedicated TEST_PAYMENT_CREDENTIAL_POSTGRES_DSN is not configured")
}
config, err := url.Parse(dsn)
require.NoError(t, err)
require.Equal(t, "/payment_credential_verify", config.Path)
require.Contains(t, []string{"127.0.0.1", "localhost"}, config.Hostname())
require.Empty(t, config.Query().Get("dbname"))
case "sqlite":
common.SQLitePath = filepath.Join(t.TempDir(), "credential.db")
}
t.Setenv("PAYMENT_CREDENTIAL_TEST_DSN", dsn)
db, dbType, err := chooseDB("PAYMENT_CREDENTIAL_TEST_DSN", false)
require.NoError(t, err)
db = paymentCredentialDB(db)
oldDB, oldDBType := DB, common.MainDatabaseType()
oldMap := common.OptionMap
oldEpayID := operation_setting.EpayId
oldValues := make(map[string]string)
for name, value := range paymentCredentialOptionValues {
oldValues[name] = *value
}
DB = db
common.SetMainDatabaseType(dbType)
initCol()
common.OptionMap = make(map[string]string)
t.Cleanup(func() {
assert.NoError(t, closeDB(db))
DB, common.SQLitePath, common.OptionMap = oldDB, oldPath, oldMap
operation_setting.EpayId = oldEpayID
common.SetMainDatabaseType(oldDBType)
initCol()
for name, value := range oldValues {
*paymentCredentialOptionValues[name] = value
}
})
var version string
if dialect == "sqlite" {
require.NoError(t, db.Raw("SELECT sqlite_version()").Scan(&version).Error)
} else {
require.NoError(t, db.Raw("SELECT version()").Scan(&version).Error)
}
t.Logf("database version: %s", version)
storageModels := []any{&Option{}, &AlipayDirectCredentials{}, &AlipayDirectOrder{}, &paymentCredentialOption{}, &SystemTask{}, &TopUp{}, &SubscriptionOrder{}, &paymentGatewayRevision{}}
require.NoError(t, db.Migrator().DropTable(storageModels...))
require.NoError(t, db.AutoMigrate(storageModels...))
t.Setenv("PAYMENT_CREDENTIAL_KEY", "")
require.NoError(t, initializePaymentCredentialStorage(db, true))
require.NoError(t, initializePaymentCredentialStorage(db, true))
require.NoError(t, initializePaymentCredentialStorage(db, false))
require.NoError(t, db.Migrator().DropTable(&paymentCredentialOption{}))
// Existing non-Alipay gateways stored their settings in plaintext.
for name := range paymentCredentialOptionValues {
require.NoError(t, db.Create(&Option{Key: name, Value: "old-secret-for-" + name}).Error)
}
require.NoError(t, db.Create(&Option{Key: "EpayId", Value: "ordinary-merchant-id"}).Error)
require.NoError(t, db.AutoMigrate(&paymentCredentialOption{}))
require.ErrorIs(t, initializePaymentCredentialStorage(db, true), ErrPaymentCredentialKey)
var count int64
require.NoError(t, db.Model(&paymentCredentialOption{}).Count(&count).Error)
assert.Zero(t, count, "failed migration must roll back vault rows and its marker")
require.NoError(t, db.Model(&Option{}).Where(paymentCredentialOptionKeys).Count(&count).Error)
assert.EqualValues(t, len(paymentCredentialOptionValues), count)
rootKey := base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{2}, 32))
t.Setenv("PAYMENT_CREDENTIAL_KEY", rootKey)
oldSessionSecret := common.SessionSecret
common.SessionSecret = rootKey
assert.False(t, PaymentCredentialKeyConfigured())
common.SessionSecret = oldSessionSecret
require.ErrorIs(t, initializePaymentCredentialStorage(db, false), errPaymentCredentialMigrationRequired)
require.NoError(t, initializePaymentCredentialStorage(db, true))
// Alipay uses the common root key from its first save. Restarts verify its
// ciphertext while leaving the order's original revision reference intact.
aead, err := alipayDirectCipher()
require.NoError(t, err)
for idx := range 2 {
revision := AlipayDirectCredentials{Id: 40 + idx, MerchantId: 12, AppId: "345", SellerId: "678", Sandbox: true}
plain, err := common.Marshal(alipayDirectKeys{PrivateKey: fmt.Sprintf("alipay-private-%d", idx), AlipayPublicKey: "alipay-public"})
require.NoError(t, err)
revision.EncryptedKeys = sealPaymentCredential(aead, paymentCredentialAlipayPrefix, revision.encryptionContext(), plain)
require.NoError(t, db.Create(&revision).Error)
}
order := AlipayDirectOrder{TradeNo: "credential-restart-order", RequestHash: "restart-request", MerchantId: 12, RevisionId: 40, Status: AlipayDirectStatusPending}
require.NoError(t, db.Create(&order).Error)
var savedOrder AlipayDirectOrder
require.NoError(t, db.Take(&savedOrder, order.Id).Error)
rev, err := GetAlipayDirectCredentials(savedOrder.RevisionId)
require.NoError(t, err)
assert.Equal(t, 40, rev.Id)
assert.Equal(t, "alipay-private-0", rev.PrivateKey)
assert.Equal(t, "alipay-public", rev.AlipayPublicKey)
newer, err := GetAlipayDirectCredentials(41)
require.NoError(t, err)
assert.Equal(t, "alipay-private-1", newer.PrivateKey)
require.NoError(t, initializePaymentCredentialStorage(db, true))
require.NoError(t, initializePaymentCredentialStorage(db, false))
retained, err := GetAlipayDirectCredentials(40)
require.NoError(t, err)
assert.Equal(t, rev.EncryptedKeys, retained.EncryptedKeys)
encodedRevision, err := common.Marshal(retained)
require.NoError(t, err)
assert.NotContains(t, string(encodedRevision), retained.PrivateKey)
require.NoError(t, db.Model(&Option{}).Where(paymentCredentialOptionKeys).Count(&count).Error)
assert.Zero(t, count)
require.NoError(t, LoadOptionsFromDatabase())
for name, value := range paymentCredentialOptionValues {
assert.Equal(t, "old-secret-for-"+name, *value)
assert.NotContains(t, common.OptionMap, name)
}
visible, err := AllOption()
require.NoError(t, err)
require.Len(t, visible, 1)
assert.Equal(t, "EpayId", visible[0].Key)
require.NoError(t, UpdateOption("EpayKey", "rotated-key"))
require.NoError(t, UpdateOptionsBulk(map[string]string{"StripeApiSecret": "stripe-new-secret", "EpayId": "changed-id"}))
var stripe paymentCredentialOption
require.NoError(t, db.Take(&stripe, "name = ?", "StripeApiSecret").Error)
assert.NotContains(t, stripe.Ciphertext, "stripe-new-secret")
assert.Equal(t, "rotated-key", *paymentCredentialOptionValues["EpayKey"])
assert.Equal(t, "stripe-new-secret", *paymentCredentialOptionValues["StripeApiSecret"])
require.ErrorIs(t, UpdateOptionsBulk(map[string]string{"StripeApiSecret": "mixed-secret", "passkey.rp_id": "example.test"}), errPaymentCredentialMixedPasskey)
// Changing the draft or stopping it must fence a checkout that already read
// the previous activation. Both new and pre-versioning orders remain verifiable.
provider := PaymentProviderWaffoPancake
draftKey := "WaffoPancakePrivateKey"
legacyOrder := TopUp{TradeNo: "legacy-pancake", PaymentProvider: provider}
require.NoError(t, db.Create(&legacyOrder).Error)
legacyDraft, err := PaymentGatewayDraft(provider)
require.NoError(t, err)
require.NoError(t, UpdateOption(draftKey, "second-pancake-key"))
require.ErrorIs(t, SetPaymentGatewayConfiguration(provider, legacyDraft), ErrPaymentGatewayChanged)
_, err = PaymentGatewayActiveConfiguration(provider)
require.ErrorIs(t, err, ErrPaymentGatewayUnavailable)
newDraft, err := PaymentGatewayDraft(provider)
require.NoError(t, err)
require.NoError(t, SetPaymentGatewayConfiguration(provider, newDraft))
active, err := PaymentGatewayActiveConfiguration(provider)
require.NoError(t, err)
versionedOrder := TopUp{TradeNo: "versioned-pancake", PaymentProvider: provider}
require.NoError(t, versionedOrder.InsertGatewayOrder(active.RevisionID))
require.ErrorIs(t, ClearPaymentGatewayConfig(provider), ErrPaymentGatewayMustStop)
require.NoError(t, StopPaymentGatewayRevision(provider, active.RevisionID))
lateOrder := SubscriptionOrder{TradeNo: "late-pancake", PaymentProvider: provider}
require.ErrorIs(t, lateOrder.InsertGatewayOrder(active.RevisionID), ErrPaymentGatewayUnavailable)
require.NoError(t, SetPaymentGatewayConfiguration(provider, newDraft))
require.NoError(t, StopPaymentGatewayRevision(provider, active.RevisionID))
reactivated, err := PaymentGatewayActiveConfiguration(provider)
require.NoError(t, err)
assert.NotEqual(t, active.RevisionID, reactivated.RevisionID)
require.NoError(t, SetPaymentGatewayConfiguration(provider, nil))
require.ErrorIs(t, ActivatePaymentGateway(provider, func(map[string]string) error {
return SetPaymentGatewayConfiguration(provider, nil)
}), ErrPaymentGatewayChanged)
require.NoError(t, ClearPaymentGatewayConfig(provider))
cleared, err := PaymentGatewayDraft(provider)
require.NoError(t, err)
assert.Empty(t, cleared[draftKey])
assert.Empty(t, cleared["WaffoPancakeStoreID"])
oldOrderConfig, err := OrderPaymentGatewayConfiguration(provider, legacyOrder.TradeNo, true, false)
require.NoError(t, err)
assert.Equal(t, legacyDraft[draftKey], oldOrderConfig[draftKey])
orderConfig, err := OrderPaymentGatewayConfiguration(provider, versionedOrder.TradeNo, true, false)
require.NoError(t, err)
assert.Equal(t, "second-pancake-key", orderConfig[draftKey])
_, err = OrderPaymentGatewayConfiguration(PaymentProviderStripe, versionedOrder.TradeNo, true, false)
require.ErrorIs(t, err, gorm.ErrRecordNotFound)
require.NoError(t, initializePaymentCredentialStorage(db, true))
require.NoError(t, initializePaymentCredentialStorage(db, false))
// Ciphertext is bound to its option and fails closed even on a live reload.
require.NoError(t, db.Model(&paymentCredentialOption{}).Where("name = ?", "EpayKey").Update("ciphertext", stripe.Ciphertext).Error)
require.ErrorIs(t, LoadOptionsFromDatabase(), errPaymentCredentialData)
assert.Empty(t, *paymentCredentialOptionValues["EpayKey"])
assert.Empty(t, *paymentCredentialOptionValues["StripeApiSecret"])
require.NoError(t, db.Transaction(func(tx *gorm.DB) error {
return ClearPaymentCredentialOptionsTx(tx, []string{"EpayKey"})
}))
require.NoError(t, RefreshPaymentCredentialOptions())
assert.Empty(t, *paymentCredentialOptionValues["EpayKey"])
assert.Equal(t, "stripe-new-secret", *paymentCredentialOptionValues["StripeApiSecret"])
t.Setenv("PAYMENT_CREDENTIAL_KEY", base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{3}, 32)))
require.ErrorIs(t, initializePaymentCredentialStorage(db, false), errPaymentCredentialData)
_, err = GetAlipayDirectCredentials(40)
require.ErrorIs(t, err, errPaymentCredentialData)
t.Setenv("PAYMENT_CREDENTIAL_KEY", "")
require.ErrorIs(t, UpdateOptionsBulk(map[string]string{"EpayId": "must-roll-back", "StripeApiSecret": "forbidden"}), ErrPaymentCredentialKey)
var visibleOption Option
require.NoError(t, db.Take(&visibleOption, commonKeyCol+" = ?", "EpayId").Error)
assert.Equal(t, "changed-id", visibleOption.Value)
assert.Equal(t, "stripe-new-secret", *paymentCredentialOptionValues["StripeApiSecret"])
}
func TestAlipayDirectDatabaseMatrix(t *testing.T) {
for _, dialect := range []string{"sqlite", "mysql", "postgres"} {
t.Run(dialect, func(t *testing.T) {
@@ -45,7 +273,7 @@ func TestAlipayDirectDatabaseMatrix(t *testing.T) {
common.SQLitePath = filepath.Join(t.TempDir(), "alipay.db") + "?_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)&_pragma=synchronous(NORMAL)"
}
t.Setenv("ALIPAY_TEST_DSN", dsn)
t.Setenv("ALIPAY_DIRECT_KEY", base64.StdEncoding.EncodeToString(make([]byte, 32)))
t.Setenv("PAYMENT_CREDENTIAL_KEY", base64.StdEncoding.EncodeToString(make([]byte, 32)))
db, dbType, err := chooseDB("ALIPAY_TEST_DSN", false)
require.NoError(t, err)
db = db.Session(&gorm.Session{Logger: gormlogger.Default.LogMode(gormlogger.Silent)})
+5
View File
@@ -383,6 +383,8 @@ func migrateDB() error {
&UserBulkBatch{},
&UserBulkItem{},
&PaymentReceipt{},
&paymentCredentialOption{},
&paymentGatewayRevision{},
&AlipayDirectSettings{},
&AlipayDirectMerchant{},
&AlipayDirectCredentials{},
@@ -399,6 +401,9 @@ func migrateDB() error {
if err != nil {
return err
}
if err := initializePaymentCredentialStorage(DB, true); err != nil {
return err
}
if err := migrateSupportTicketStatuses(DB); err != nil {
return err
}
+56 -43
View File
@@ -2,6 +2,7 @@ package model
import (
"maps"
"slices"
"strconv"
"strings"
"time"
@@ -25,9 +26,12 @@ type Option struct {
func AllOption() ([]*Option, error) {
var options []*Option
var err error
err = DB.Find(&options).Error
return options, err
if err := DB.Not(paymentCredentialOptionKeys).Find(&options).Error; err != nil {
return nil, err
}
return slices.DeleteFunc(options, func(option *Option) bool {
return IsPaymentCredentialOption(option.Key)
}), nil
}
func InitOptionMap() {
@@ -91,27 +95,16 @@ func InitOptionMap() {
common.OptionMap["PayAddress"] = ""
common.OptionMap["CustomCallbackAddress"] = ""
common.OptionMap["EpayId"] = ""
common.OptionMap["EpayKey"] = ""
common.OptionMap["Price"] = strconv.FormatFloat(operation_setting.Price, 'f', -1, 64)
common.OptionMap["USDExchangeRate"] = strconv.FormatFloat(operation_setting.USDExchangeRate, 'f', -1, 64)
common.OptionMap["MinTopUp"] = strconv.Itoa(operation_setting.MinTopUp)
common.OptionMap["StripeMinTopUp"] = strconv.Itoa(setting.StripeMinTopUp)
common.OptionMap["StripeApiSecret"] = setting.StripeApiSecret
common.OptionMap["StripeWebhookSecret"] = setting.StripeWebhookSecret
common.OptionMap["StripePriceId"] = setting.StripePriceId
common.OptionMap["StripeUnitPrice"] = strconv.FormatFloat(setting.StripeUnitPrice, 'f', -1, 64)
common.OptionMap["StripePromotionCodesEnabled"] = strconv.FormatBool(setting.StripePromotionCodesEnabled)
common.OptionMap["CreemApiKey"] = setting.CreemApiKey
common.OptionMap["CreemProducts"] = setting.CreemProducts
common.OptionMap["CreemTestMode"] = strconv.FormatBool(setting.CreemTestMode)
common.OptionMap["CreemWebhookSecret"] = setting.CreemWebhookSecret
common.OptionMap["WaffoEnabled"] = strconv.FormatBool(setting.WaffoEnabled)
common.OptionMap["WaffoApiKey"] = setting.WaffoApiKey
common.OptionMap["WaffoPrivateKey"] = setting.WaffoPrivateKey
common.OptionMap["WaffoPublicCert"] = setting.WaffoPublicCert
common.OptionMap["WaffoSandboxPublicCert"] = setting.WaffoSandboxPublicCert
common.OptionMap["WaffoSandboxApiKey"] = setting.WaffoSandboxApiKey
common.OptionMap["WaffoSandboxPrivateKey"] = setting.WaffoSandboxPrivateKey
common.OptionMap["WaffoSandbox"] = strconv.FormatBool(setting.WaffoSandbox)
common.OptionMap["WaffoMerchantId"] = setting.WaffoMerchantId
common.OptionMap["WaffoNotifyUrl"] = setting.WaffoNotifyUrl
@@ -122,7 +115,6 @@ func InitOptionMap() {
common.OptionMap["WaffoMinTopUp"] = strconv.Itoa(setting.WaffoMinTopUp)
common.OptionMap["WaffoPayMethods"] = setting.WaffoPayMethods2JsonString()
common.OptionMap["WaffoPancakeMerchantID"] = setting.WaffoPancakeMerchantID
common.OptionMap["WaffoPancakePrivateKey"] = setting.WaffoPancakePrivateKey
common.OptionMap["WaffoPancakeReturnURL"] = setting.WaffoPancakeReturnURL
common.OptionMap["WaffoPancakeUnitPrice"] = strconv.FormatFloat(setting.WaffoPancakeUnitPrice, 'f', -1, 64)
common.OptionMap["WaffoPancakeMinTopUp"] = strconv.Itoa(setting.WaffoPancakeMinTopUp)
@@ -187,6 +179,9 @@ func InitOptionMap() {
// 自动添加所有注册的模型配置
modelConfigs := config.GlobalConfig.ExportAllConfigs()
for _, name := range paymentCredentialOptionNames {
delete(modelConfigs, name)
}
maps.Copy(common.OptionMap, modelConfigs)
common.OptionMapRWMutex.Unlock()
@@ -202,6 +197,7 @@ func LoadOptionsFromDatabase() error {
defer requestPolicyOptionMutex.Unlock()
passkeyOptionMutex.Lock()
defer passkeyOptionMutex.Unlock()
credentialErr := RefreshPaymentCredentialOptions()
options, err := AllOption()
if err != nil {
return err
@@ -223,7 +219,7 @@ func LoadOptionsFromDatabase() error {
}
}
applyPasskeyDomainOptions(passkeyOptions)
return nil
return credentialErr
}
func SyncOptions(frequency int) {
@@ -237,6 +233,15 @@ func SyncOptions(frequency int) {
}
func validateOptionValue(key string, value string) error {
if PaymentGatewayStateOption(key) {
return ErrPaymentGatewayUnavailable
}
if provider := paymentGatewayOptionProvider(key); provider != "" && !slices.Contains(paymentGatewayOptions[provider], key) {
return ErrPaymentGatewayUnavailable
}
if IsPaymentCredentialOption(key) && paymentCredentialOptionValues[key] == nil {
return errPaymentCredentialData
}
if key == legacyAccessTokenRetireAtKey {
return errLegacyRetireAtReadOnly
}
@@ -293,7 +298,7 @@ func validateOptionValue(key string, value string) error {
}
func UpdateOption(key string, value string) error {
if key == operation_setting.CustomTopUpAmountOptionKey {
if paymentGatewayOptionProvider(key) != "" || key == operation_setting.CustomTopUpAmountOptionKey {
return UpdateOptionsBulk(map[string]string{key: value})
}
if IsRequestPolicyOption(key) {
@@ -319,7 +324,9 @@ func UpdateOption(key string, value string) error {
// Save is a combination function.
// If save value does not contain primary key, it will execute Create,
// otherwise it will execute Update (with all fields).
DB.Save(&option)
if err := DB.Save(&option).Error; err != nil {
return err
}
BumpSyncTopic(SyncTopicOptions)
// Update OptionMap
return updateOptionMap(key, value)
@@ -365,8 +372,31 @@ func UpdateOptionsBulk(values map[string]string) error {
}
}
var credentials map[string]string
for k, v := range values {
if IsPaymentCredentialOption(k) {
if credentials == nil {
credentials = make(map[string]string)
}
credentials[k] = v
}
}
if len(credentials) != 0 {
paymentCredentialOptionMutex.Lock()
defer paymentCredentialOptionMutex.Unlock()
}
err := DB.Transaction(func(tx *gorm.DB) error {
for k, v := range values {
if err := fencePaymentGatewayOptionWrites(tx, values); err != nil {
return err
}
for _, k := range slices.Sorted(maps.Keys(values)) {
v := values[k]
if _, protected := credentials[k]; protected {
if err := persistPaymentCredentialOption(tx, k, v); err != nil {
return err
}
continue
}
option := Option{Key: k}
if err := tx.FirstOrCreate(&option, Option{Key: k}).Error; err != nil {
return err
@@ -381,8 +411,12 @@ func UpdateOptionsBulk(values map[string]string) error {
if err != nil {
return err
}
applyPaymentCredentialOptions(credentials, false)
BumpSyncTopic(SyncTopicOptions)
for k, v := range values {
if _, protected := credentials[k]; protected {
continue
}
if err := updateOptionMap(k, v); err != nil {
return err
}
@@ -394,6 +428,9 @@ func UpdateOptionsBulk(values map[string]string) error {
}
func updateOptionMap(key string, value string) (err error) {
if IsPaymentCredentialOption(key) {
return errPaymentCredentialData
}
if key == retiredThemeOptionKey || key == legacyAccessTokenRetireAtKey {
common.OptionMapRWMutex.Lock()
delete(common.OptionMap, key)
@@ -548,18 +585,12 @@ func updateOptionMap(key string, value string) (err error) {
operation_setting.CustomCallbackAddress = value
case "EpayId":
operation_setting.EpayId = value
case "EpayKey":
operation_setting.EpayKey = value
case "Price":
operation_setting.Price, _ = strconv.ParseFloat(value, 64)
case "USDExchangeRate":
operation_setting.USDExchangeRate, _ = strconv.ParseFloat(value, 64)
case "MinTopUp":
operation_setting.MinTopUp, _ = strconv.Atoi(value)
case "StripeApiSecret":
setting.StripeApiSecret = value
case "StripeWebhookSecret":
setting.StripeWebhookSecret = value
case "StripePriceId":
setting.StripePriceId = value
case "StripeUnitPrice":
@@ -568,28 +599,12 @@ func updateOptionMap(key string, value string) (err error) {
setting.StripeMinTopUp, _ = strconv.Atoi(value)
case "StripePromotionCodesEnabled":
setting.StripePromotionCodesEnabled = value == "true"
case "CreemApiKey":
setting.CreemApiKey = value
case "CreemProducts":
setting.CreemProducts = value
case "CreemTestMode":
setting.CreemTestMode = value == "true"
case "CreemWebhookSecret":
setting.CreemWebhookSecret = value
case "WaffoEnabled":
setting.WaffoEnabled = value == "true"
case "WaffoApiKey":
setting.WaffoApiKey = value
case "WaffoPrivateKey":
setting.WaffoPrivateKey = value
case "WaffoPublicCert":
setting.WaffoPublicCert = value
case "WaffoSandboxPublicCert":
setting.WaffoSandboxPublicCert = value
case "WaffoSandboxApiKey":
setting.WaffoSandboxApiKey = value
case "WaffoSandboxPrivateKey":
setting.WaffoSandboxPrivateKey = value
case "WaffoSandbox":
setting.WaffoSandbox = value == "true"
case "WaffoMerchantId":
@@ -608,8 +623,6 @@ func updateOptionMap(key string, value string) (err error) {
setting.WaffoMinTopUp, _ = strconv.Atoi(value)
case "WaffoPancakeMerchantID":
setting.WaffoPancakeMerchantID = value
case "WaffoPancakePrivateKey":
setting.WaffoPancakePrivateKey = value
case "WaffoPancakeReturnURL":
setting.WaffoPancakeReturnURL = value
case "WaffoPancakeStoreID":
+3
View File
@@ -98,6 +98,9 @@ func UpdatePasskeyDomainOptions(values map[string]string, preview bool, confirma
defer passkeyOptionMutex.Unlock()
values = maps.Clone(values)
for key, value := range values {
if PaymentGatewayStateOption(key) || paymentGatewayOptionProvider(key) != "" {
return nil, errPaymentCredentialMixedPasskey
}
if err := validateOptionValue(key, value); err != nil {
return nil, err
}
+234
View File
@@ -0,0 +1,234 @@
package model
import (
"crypto/aes"
"crypto/cipher"
"crypto/hkdf"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"errors"
"maps"
"os"
"slices"
"strings"
"sync"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/setting"
"github.com/QuantumNous/new-api/setting/operation_setting"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"gorm.io/gorm/logger"
)
const (
paymentCredentialOptionPurpose = "provider-options/v1"
paymentCredentialAlipayPurpose = "alipay-direct/v2"
paymentCredentialOptionPrefix = "v1:"
paymentCredentialAlipayPrefix = "v2:"
)
var (
ErrPaymentCredentialKey = common.NewMessage("PAYMENT_CREDENTIAL_KEY must be a separate base64-encoded 32-byte key")
errPaymentCredentialData = errors.New("payment credential data is unreadable")
errPaymentCredentialStore = errors.New("payment credential storage operation failed")
errPaymentCredentialMigrationRequired = errors.New("payment credential migration must finish on the database master before startup")
errPaymentCredentialMixedPasskey = common.NewMessage("Save payment credentials separately from passkey domains")
// Serialize option refresh and credential publication within this process.
paymentCredentialOptionMutex sync.Mutex
paymentCredentialOptionValues = map[string]*string{
"EpayKey": &operation_setting.EpayKey,
operation_setting.EpayMerchantPrivateKeyOptionKey: &operation_setting.GetPaymentSetting().EpayMerchantPrivateKey,
operation_setting.EpayPlatformPublicKeyOptionKey: &operation_setting.GetPaymentSetting().EpayPlatformPublicKey,
"StripeApiSecret": &setting.StripeApiSecret,
"StripeWebhookSecret": &setting.StripeWebhookSecret,
"CreemApiKey": &setting.CreemApiKey,
"CreemWebhookSecret": &setting.CreemWebhookSecret,
"WaffoApiKey": &setting.WaffoApiKey,
"WaffoPrivateKey": &setting.WaffoPrivateKey,
"WaffoPublicCert": &setting.WaffoPublicCert,
"WaffoSandboxApiKey": &setting.WaffoSandboxApiKey,
"WaffoSandboxPrivateKey": &setting.WaffoSandboxPrivateKey,
"WaffoSandboxPublicCert": &setting.WaffoSandboxPublicCert,
"WaffoPancakePrivateKey": &setting.WaffoPancakePrivateKey,
}
paymentCredentialOptionNames = slices.Sorted(maps.Keys(paymentCredentialOptionValues))
paymentCredentialOptionKeys = func() clause.IN {
keys := make([]any, 0, len(paymentCredentialOptionNames))
for _, name := range paymentCredentialOptionNames {
keys = append(keys, name)
}
return clause.IN{Column: clause.Column{Name: "key"}, Values: keys}
}()
)
// IsPaymentCredentialOption identifies option names that must never be returned
// by option endpoints. Treat aliases conservatively for case-insensitive SQL.
func IsPaymentCredentialOption(key string) bool {
key = strings.TrimRight(key, " ")
return slices.ContainsFunc(paymentCredentialOptionNames, func(name string) bool {
return strings.EqualFold(name, key)
})
}
type paymentCredentialOption struct {
Name string `gorm:"size:64;primaryKey"`
Ciphertext string `gorm:"not null"`
}
func paymentCredentialRootKey() ([]byte, error) {
encoded := os.Getenv("PAYMENT_CREDENTIAL_KEY")
key, err := base64.StdEncoding.Strict().DecodeString(encoded)
if err != nil || len(key) != 32 || base64.StdEncoding.EncodeToString(key) != encoded {
return nil, ErrPaymentCredentialKey
}
// Refuse reuse whether a session uses the literal encoded secret or the
// underlying bytes. The session secret itself is never a key source.
if subtle.ConstantTimeCompare([]byte(common.SessionSecret), []byte(encoded)) == 1 ||
subtle.ConstantTimeCompare([]byte(common.SessionSecret), key) == 1 {
return nil, ErrPaymentCredentialKey
}
return key, nil
}
func PaymentCredentialKeyConfigured() bool {
_, err := paymentCredentialRootKey()
return err == nil
}
func paymentCredentialCipher(root []byte, purpose string) (cipher.AEAD, error) {
key, err := hkdf.Key(sha256.New, root, nil, "new-api/payment-credentials/"+purpose, 32)
if err != nil {
return nil, errPaymentCredentialData
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, errPaymentCredentialData
}
return cipher.NewGCMWithRandomNonce(block)
}
func sealPaymentCredential(aead cipher.AEAD, prefix string, context, plaintext []byte) string {
return prefix + base64.StdEncoding.EncodeToString(aead.Seal(nil, nil, plaintext, context))
}
func openPaymentCredential(aead cipher.AEAD, prefix, value string, context []byte) ([]byte, error) {
payload, ok := strings.CutPrefix(value, prefix)
if !ok {
return nil, errPaymentCredentialData
}
sealed, err := base64.StdEncoding.Strict().DecodeString(payload)
if err != nil || len(sealed) < aead.NonceSize()+aead.Overhead() {
return nil, errPaymentCredentialData
}
plain, err := aead.Open(nil, sealed[:aead.NonceSize()], sealed[aead.NonceSize():], context)
if err != nil {
return nil, errPaymentCredentialData
}
return plain, nil
}
// Payment credential SQL and driver errors can contain data values, even if
// the SQL logger parameterizes the query text. Silence these queries in debug
// mode as well and return fixed operation errors at the storage boundary.
func paymentCredentialDB(db *gorm.DB) *gorm.DB {
return db.Session(&gorm.Session{Logger: logger.Default.LogMode(logger.Silent)})
}
func persistPaymentCredentialOption(db *gorm.DB, name, value string) error {
db = paymentCredentialDB(db)
if value == "" {
if err := db.Delete(&paymentCredentialOption{}, "name = ?", name).Error; err != nil {
return errPaymentCredentialStore
}
return nil
}
root, err := paymentCredentialRootKey()
if err != nil {
return err
}
aead, err := paymentCredentialCipher(root, paymentCredentialOptionPurpose)
if err != nil {
return err
}
row := paymentCredentialOption{Name: name, Ciphertext: sealPaymentCredential(aead, paymentCredentialOptionPrefix, []byte(name), []byte(value))}
if err := db.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "name"}}, DoUpdates: clause.AssignmentColumns([]string{"ciphertext"})}).Create(&row).Error; err != nil {
return errPaymentCredentialStore
}
return nil
}
func readPaymentCredentialOptions(db *gorm.DB) (map[string]string, error) {
return readPaymentCredentialOptionsFor(db, paymentCredentialOptionNames)
}
func readPaymentCredentialOptionsFor(db *gorm.DB, names []string) (map[string]string, error) {
var rows []paymentCredentialOption
if err := paymentCredentialDB(db).Where("name IN ?", names).Find(&rows).Error; err != nil {
return nil, errPaymentCredentialStore
}
if len(rows) == 0 {
return nil, nil
}
root, err := paymentCredentialRootKey()
if err != nil {
return nil, err
}
aead, err := paymentCredentialCipher(root, paymentCredentialOptionPurpose)
if err != nil {
return nil, err
}
values := make(map[string]string, len(rows))
for _, row := range rows {
if paymentCredentialOptionValues[row.Name] == nil {
return nil, errPaymentCredentialData
}
plain, err := openPaymentCredential(aead, paymentCredentialOptionPrefix, row.Ciphertext, []byte(row.Name))
if err != nil || len(plain) == 0 {
return nil, errPaymentCredentialData
}
values[row.Name] = string(plain)
}
return values, nil
}
// ClearPaymentCredentialOptionsTx removes the specified credentials as part of
// the caller's configuration transaction. Refresh runtime settings after commit.
func ClearPaymentCredentialOptionsTx(tx *gorm.DB, keys []string) error {
if len(keys) == 0 {
return nil
}
for _, key := range keys {
if paymentCredentialOptionValues[key] == nil {
return errPaymentCredentialData
}
}
if err := paymentCredentialDB(tx).Delete(&paymentCredentialOption{}, "name IN ?", keys).Error; err != nil {
return errPaymentCredentialStore
}
return nil
}
// RefreshPaymentCredentialOptions reloads credentials after an external
// transaction. An unreadable vault invalidates cached payment credentials.
func RefreshPaymentCredentialOptions() error {
paymentCredentialOptionMutex.Lock()
defer paymentCredentialOptionMutex.Unlock()
values, err := readPaymentCredentialOptions(DB)
applyPaymentCredentialOptions(values, true)
return err
}
func applyPaymentCredentialOptions(values map[string]string, reset bool) {
common.OptionMapRWMutex.Lock()
defer common.OptionMapRWMutex.Unlock()
for name, settingValue := range paymentCredentialOptionValues {
value, changed := values[name]
if reset || changed {
*settingValue = value
delete(common.OptionMap, name)
}
}
}
+109
View File
@@ -0,0 +1,109 @@
package model
import (
"crypto/cipher"
"os"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
const paymentCredentialStorageVersion = "__storage_version"
// VerifyPaymentCredentialStorage runs before a worker starts serving requests.
func VerifyPaymentCredentialStorage() error {
return initializePaymentCredentialStorage(DB, false)
}
// On the master the marker and option migration commit together. The first
// write takes SQLite's writer lock before reading the legacy options.
// Other nodes only verify the committed format and their local encryption key.
func initializePaymentCredentialStorage(db *gorm.DB, master bool) error {
if os.Getenv("PAYMENT_CREDENTIAL_KEY") != "" && !PaymentCredentialKeyConfigured() {
return ErrPaymentCredentialKey
}
db = paymentCredentialDB(db)
return db.Transaction(func(tx *gorm.DB) error {
if master {
if err := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&paymentCredentialOption{Name: paymentCredentialStorageVersion, Ciphertext: "0"}).Error; err != nil {
return errPaymentCredentialStore
}
}
query := tx
if master {
query = lockForUpdate(tx)
}
var marker paymentCredentialOption
if err := query.Take(&marker, "name = ?", paymentCredentialStorageVersion).Error; err != nil {
if !master {
return errPaymentCredentialMigrationRequired
}
return errPaymentCredentialStore
}
migrating := master && marker.Ciphertext == "0"
if !migrating && marker.Ciphertext != "1" {
return errPaymentCredentialMigrationRequired
}
if err := migratePaymentCredentialOptions(tx, migrating); err != nil {
return err
}
if err := validateStoredAlipayDirectCredentials(tx); err != nil {
return err
}
if err := validateStoredPaymentGatewayRevisions(tx); err != nil {
return err
}
if migrating {
if err := tx.Model(&marker).Update("ciphertext", "1").Error; err != nil {
return errPaymentCredentialStore
}
}
return nil
})
}
func migratePaymentCredentialOptions(tx *gorm.DB, migrating bool) error {
var rows []Option
if err := tx.Where(paymentCredentialOptionKeys).Find(&rows).Error; err != nil {
return errPaymentCredentialStore
}
if len(rows) != 0 && !migrating {
return errPaymentCredentialMigrationRequired
}
current, err := readPaymentCredentialOptions(tx)
if err != nil {
return err
}
for _, row := range rows {
if paymentCredentialOptionValues[row.Key] == nil || current[row.Key] != "" {
return errPaymentCredentialData
}
if err := persistPaymentCredentialOption(tx, row.Key, row.Value); err != nil {
return err
}
if err := tx.Delete(&Option{}, commonKeyCol+" = ?", row.Key).Error; err != nil {
return errPaymentCredentialStore
}
}
return nil
}
func validateStoredAlipayDirectCredentials(db *gorm.DB) error {
var revisions []AlipayDirectCredentials
var aead cipher.AEAD
return db.FindInBatches(&revisions, 100, func(_ *gorm.DB, _ int) error {
if aead == nil {
var err error
aead, err = alipayDirectCipher()
if err != nil {
return err
}
}
for _, revision := range revisions {
if _, err := revision.openKeys(aead); err != nil {
return err
}
}
return nil
}).Error
}
+449
View File
@@ -0,0 +1,449 @@
package model
import (
"errors"
"maps"
"slices"
"strconv"
"strings"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/setting/operation_setting"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
var (
ErrPaymentGatewayUnavailable = common.NewMessage("Payment gateway is unavailable")
ErrPaymentGatewayMustStop = common.NewMessage("Stop the payment gateway before clearing its configuration")
ErrPaymentGatewayChanged = common.NewMessage("Payment gateway configuration changed. Try again.")
)
const paymentGatewayOptionPrefix = "payment_gateway."
var paymentGatewayOptions = map[string][]string{
PaymentProviderEpay: {"PayAddress", "CustomCallbackAddress", "EpayId", "EpayKey", "PayMethods", operation_setting.EpaySignTypeOptionKey, operation_setting.EpayMerchantPrivateKeyOptionKey, operation_setting.EpayPlatformPublicKeyOptionKey},
PaymentProviderStripe: {"StripeApiSecret", "StripeWebhookSecret", "StripePriceId"},
PaymentProviderCreem: {"CreemApiKey", "CreemWebhookSecret", "CreemProducts", "CreemTestMode"},
PaymentProviderWaffo: {"WaffoMerchantId", "WaffoNotifyUrl", "WaffoReturnUrl", "WaffoSubscriptionReturnUrl", "WaffoEnabled", "WaffoSandbox", "WaffoPayMethods", "WaffoApiKey", "WaffoPrivateKey", "WaffoPublicCert", "WaffoSandboxApiKey", "WaffoSandboxPrivateKey", "WaffoSandboxPublicCert"},
PaymentProviderWaffoPancake: {"WaffoPancakeMerchantID", "WaffoPancakeReturnURL", "WaffoPancakeStoreID", "WaffoPancakeProductID", "WaffoPancakePrivateKey"},
}
type paymentGatewayRevision struct {
Id int `gorm:"primaryKey"`
Provider string `gorm:"size:32;not null"`
Ciphertext string `gorm:"type:text;not null"`
}
// PaymentGatewayPersistenceModels is the payment gateway lifecycle storage schema.
func PaymentGatewayPersistenceModels() []any {
return []any{&Option{}, &TopUp{}, &SubscriptionOrder{}, &paymentCredentialOption{}, &paymentGatewayRevision{}}
}
type PaymentGatewayConfiguration struct {
RevisionID int
Values map[string]string
}
func PaymentGatewayStateOption(key string) bool {
return strings.HasPrefix(strings.ToLower(key), paymentGatewayOptionPrefix)
}
func paymentGatewayOptionKey(provider string) string {
return paymentGatewayOptionPrefix + provider + ".enabled"
}
func paymentGatewayOptionProvider(key string) string {
for provider, keys := range paymentGatewayOptions {
if slices.ContainsFunc(keys, func(name string) bool { return strings.EqualFold(name, strings.TrimRight(key, " ")) }) {
return provider
}
}
return ""
}
func paymentGatewayRevisionID(row Option) int {
id, _ := strconv.Atoi(row.Value)
return id
}
func PaymentGatewayActiveConfiguration(provider string) (PaymentGatewayConfiguration, error) {
if DB == nil || paymentGatewayOptions[provider] == nil {
return PaymentGatewayConfiguration{}, ErrPaymentGatewayUnavailable
}
var row Option
if err := DB.Take(&row, commonKeyCol+" = ?", paymentGatewayOptionKey(provider)).Error; err != nil {
return PaymentGatewayConfiguration{}, ErrPaymentGatewayUnavailable
}
id := paymentGatewayRevisionID(row)
if id <= 0 {
return PaymentGatewayConfiguration{}, ErrPaymentGatewayUnavailable
}
values, err := readPaymentGatewayRevision(DB, provider, id)
return PaymentGatewayConfiguration{RevisionID: id, Values: values}, err
}
func PaymentGatewayDraft(provider string) (map[string]string, error) {
if DB == nil || paymentGatewayOptions[provider] == nil {
return nil, ErrPaymentGatewayUnavailable
}
// A concurrent save is checked again under the same state lock when the
// operator activates the validated snapshot.
return readPaymentGatewayDraft(DB, provider)
}
func readPaymentGatewayDraft(db *gorm.DB, provider string) (map[string]string, error) {
keys := paymentGatewayOptions[provider]
var rows []Option
if err := db.Where(clause.IN{Column: clause.Column{Name: "key"}, Values: optionKeyValues(keys)}).Not(paymentCredentialOptionKeys).Find(&rows).Error; err != nil {
return nil, err
}
values := make(map[string]string, len(keys))
for _, key := range keys {
values[key] = ""
}
for _, row := range rows {
values[row.Key] = row.Value
}
credentials, err := readPaymentCredentialOptionsFor(db, keys)
if err != nil {
return nil, err
}
maps.Copy(values, credentials)
return values, nil
}
func optionKeyValues(keys []string) []any {
values := make([]any, 0, len(keys))
for _, key := range keys {
values = append(values, key)
}
return values
}
func savePaymentGatewayRevision(tx *gorm.DB, provider string, values map[string]string) (int, error) {
root, err := paymentCredentialRootKey()
if err != nil {
return 0, err
}
// Reserve the ID before sealing so the ciphertext is bound to this exact
// revision and cannot be swapped with a different configuration.
db := paymentCredentialDB(tx)
row := paymentGatewayRevision{Provider: provider}
if err := db.Create(&row).Error; err != nil {
return 0, errPaymentCredentialStore
}
aead, err := paymentCredentialCipher(root, "gateway-revision/v1/"+provider)
if err != nil {
return 0, err
}
plain, err := common.Marshal(values)
if err != nil {
return 0, errPaymentCredentialData
}
sealed := sealPaymentCredential(aead, "v1:", []byte(strconv.Itoa(row.Id)), plain)
if err := db.Model(&row).Update("ciphertext", sealed).Error; err != nil {
return 0, errPaymentCredentialStore
}
return row.Id, nil
}
func readPaymentGatewayRevision(db *gorm.DB, provider string, id int) (map[string]string, error) {
var row paymentGatewayRevision
if err := paymentCredentialDB(db).Take(&row, "id = ? AND provider = ?", id, provider).Error; err != nil {
return nil, errPaymentCredentialStore
}
return row.decrypt()
}
func (row paymentGatewayRevision) decrypt() (map[string]string, error) {
root, err := paymentCredentialRootKey()
if err != nil {
return nil, err
}
aead, err := paymentCredentialCipher(root, "gateway-revision/v1/"+row.Provider)
if err != nil {
return nil, err
}
plain, err := openPaymentCredential(aead, "v1:", row.Ciphertext, []byte(strconv.Itoa(row.Id)))
if err != nil {
return nil, err
}
var values map[string]string
if err := common.Unmarshal(plain, &values); err != nil {
return nil, errPaymentCredentialData
}
return values, nil
}
func validateStoredPaymentGatewayRevisions(db *gorm.DB) error {
var revisions []paymentGatewayRevision
result := db.Session(&gorm.Session{NewDB: true}).FindInBatches(&revisions, 100, func(_ *gorm.DB, _ int) error {
for _, row := range revisions {
if paymentGatewayOptions[row.Provider] == nil {
return errPaymentCredentialData
}
if _, err := row.decrypt(); err != nil {
return err
}
}
return nil
})
return result.Error
}
func lockPaymentGatewayState(tx *gorm.DB, provider string) (Option, error) {
row := Option{Key: paymentGatewayOptionKey(provider)}
if err := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&row).Error; err != nil {
return row, err
}
err := lockForUpdate(tx).Take(&row, commonKeyCol+" = ?", row.Key).Error
return row, err
}
// ActivatePaymentGateway validates outside the transaction and fences both
// concurrent edits and a stop requested while validation is in flight.
func ActivatePaymentGateway(provider string, validate func(map[string]string) error) error {
if paymentGatewayOptions[provider] == nil {
return ErrPaymentGatewayUnavailable
}
var state Option
err := DB.Take(&state, commonKeyCol+" = ?", paymentGatewayOptionKey(provider)).Error
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return err
}
draft, err := PaymentGatewayDraft(provider)
if err != nil {
return err
}
if err := validate(draft); err != nil {
return err
}
return setPaymentGatewayConfiguration(provider, draft, &state.Value)
}
func SetPaymentGatewayConfiguration(provider string, validated map[string]string) error {
return setPaymentGatewayConfiguration(provider, validated, nil)
}
func setPaymentGatewayConfiguration(provider string, validated map[string]string, validatedState *string) error {
if paymentGatewayOptions[provider] == nil {
return ErrPaymentGatewayUnavailable
}
return DB.Transaction(func(tx *gorm.DB) error {
row, err := lockPaymentGatewayState(tx, provider)
if err != nil {
return err
}
if validated == nil {
return tx.Model(&row).Update("value", "stopped:"+common.GetUUID()).Error
}
if validatedState != nil && row.Value != *validatedState {
return ErrPaymentGatewayChanged
}
draft, err := readPaymentGatewayDraft(tx, provider)
if err != nil {
return err
}
if !maps.Equal(draft, validated) {
return ErrPaymentGatewayChanged
}
if paymentGatewayRevisionID(row) > 0 {
return nil
}
id, err := savePaymentGatewayRevision(tx, provider, validated)
if err != nil {
return err
}
return tx.Model(&row).Update("value", strconv.Itoa(id)).Error
})
}
// Shut down only the exact activation that produced the definitive error.
func StopPaymentGatewayRevision(provider string, id int) error {
if paymentGatewayOptions[provider] == nil || id <= 0 {
return ErrPaymentGatewayUnavailable
}
return DB.Model(&Option{}).Where(commonKeyCol+" = ? AND value = ?", paymentGatewayOptionKey(provider), strconv.Itoa(id)).Update("value", "stopped:"+common.GetUUID()).Error
}
func insertManagedPaymentOrder(provider string, configID int, order any) error {
if DB == nil || paymentGatewayOptions[provider] == nil || configID <= 0 {
return ErrPaymentGatewayUnavailable
}
return DB.Transaction(func(tx *gorm.DB) error {
row, err := lockPaymentGatewayState(tx, provider)
if err != nil {
return err
}
if paymentGatewayRevisionID(row) != configID {
return ErrPaymentGatewayUnavailable
}
return tx.Create(order).Error
})
}
func (topUp *TopUp) InsertGatewayOrder(configID int) error {
topUp.PaymentCredentialRevisionID = configID
return insertManagedPaymentOrder(topUp.PaymentProvider, configID, topUp)
}
func (order *SubscriptionOrder) InsertGatewayOrder(configID int) error {
order.PaymentCredentialRevisionID = configID
return insertManagedPaymentOrder(order.PaymentProvider, configID, order)
}
// Only already-attributed orders can use the pre-versioning configuration.
// A missing provider cannot be resolved from the current configuration.
func OrderPaymentGatewayConfiguration(provider, tradeNo string, wallet, subscription bool) (map[string]string, error) {
if DB == nil || strings.TrimSpace(tradeNo) == "" || paymentGatewayOptions[provider] == nil {
return nil, gorm.ErrRecordNotFound
}
var id int
query := func() *gorm.DB {
return DB.Select("payment_credential_revision_id").Where("trade_no = ? AND payment_provider = ?", tradeNo, provider)
}
if wallet {
var order TopUp
err := query().Take(&order).Error
if err == nil {
id = order.PaymentCredentialRevisionID
subscription = false
} else if !errors.Is(err, gorm.ErrRecordNotFound) || !subscription {
return nil, err
}
}
if subscription {
var order SubscriptionOrder
if err := query().Take(&order).Error; err != nil {
return nil, err
}
id = order.PaymentCredentialRevisionID
}
if id > 0 {
return readPaymentGatewayRevision(DB, provider, id)
}
// Read the draft before checking the immutable archive. A concurrent save
// must publish the archive atomically with the replacement draft.
draft, draftErr := readPaymentGatewayDraft(DB, provider)
var legacy Option
if err := DB.Take(&legacy, commonKeyCol+" = ?", paymentGatewayOptionPrefix+provider+".legacy").Error; errors.Is(err, gorm.ErrRecordNotFound) {
return draft, draftErr
} else if err != nil {
return nil, err
}
if legacy.Value == "none" {
return nil, gorm.ErrRecordNotFound
}
return readPaymentGatewayRevision(DB, provider, paymentGatewayRevisionID(legacy))
}
func archiveLegacyPaymentGateway(tx *gorm.DB, provider string, current map[string]string) error {
legacy := Option{Key: paymentGatewayOptionPrefix + provider + ".legacy"}
if err := tx.Take(&legacy, commonKeyCol+" = ?", legacy.Key).Error; !errors.Is(err, gorm.ErrRecordNotFound) {
return err
}
// Keep the exact material the old application could use immediately
// before the first change. Do not treat it as proven historical identity.
legacy.Value = "none"
for _, order := range []any{&TopUp{}, &SubscriptionOrder{}} {
var rows []int
if err := tx.Model(order).Where("payment_provider = ? AND payment_credential_revision_id = 0", provider).Limit(1).Pluck("id", &rows).Error; err != nil {
return err
}
if len(rows) > 0 {
id, err := savePaymentGatewayRevision(tx, provider, current)
if err != nil {
return err
}
legacy.Value = strconv.Itoa(id)
break
}
}
return tx.Create(&legacy).Error
}
func fencePaymentGatewayOptionWrites(tx *gorm.DB, values map[string]string) error {
providers := make(map[string]bool)
for key := range values {
if provider := paymentGatewayOptionProvider(key); provider != "" {
providers[provider] = true
}
}
for _, provider := range slices.Sorted(maps.Keys(providers)) {
row, err := lockPaymentGatewayState(tx, provider)
if err != nil {
return err
}
current, err := readPaymentGatewayDraft(tx, provider)
if err != nil {
return err
}
for _, key := range paymentGatewayOptions[provider] {
if value, ok := values[key]; !ok || value == current[key] {
continue
}
if err := archiveLegacyPaymentGateway(tx, provider, current); err != nil {
return err
}
if err := tx.Model(&row).Update("value", "stopped:"+common.GetUUID()).Error; err != nil {
return err
}
break
}
}
return nil
}
func ClearPaymentGatewayConfig(provider string) error {
keys := paymentGatewayOptions[provider]
if keys == nil {
return ErrPaymentGatewayUnavailable
}
err := DB.Transaction(func(tx *gorm.DB) error {
row, err := lockPaymentGatewayState(tx, provider)
if err != nil {
return err
}
if paymentGatewayRevisionID(row) > 0 {
return ErrPaymentGatewayMustStop
}
current, err := readPaymentGatewayDraft(tx, provider)
if err != nil {
return err
}
if err := archiveLegacyPaymentGateway(tx, provider, current); err != nil {
return err
}
var credentials []string
for _, key := range keys {
if IsPaymentCredentialOption(key) {
credentials = append(credentials, key)
continue
}
// Persist reset values so replicas also replace old in-memory options.
reset := ""
switch key {
case "PayMethods", "WaffoPayMethods", "CreemProducts":
reset = "[]"
case "WaffoEnabled", "WaffoSandbox", "CreemTestMode":
reset = "false"
case operation_setting.EpaySignTypeOptionKey:
reset = operation_setting.EpaySignTypeMD5
}
option := Option{Key: key, Value: reset}
if err := tx.Clauses(clause.OnConflict{UpdateAll: true}).Create(&option).Error; err != nil {
return err
}
}
if err := ClearPaymentCredentialOptionsTx(tx, credentials); err != nil {
return err
}
return tx.Model(&row).Update("value", "stopped:"+common.GetUUID()).Error
})
if err != nil {
return err
}
BumpSyncTopic(SyncTopicOptions)
return LoadOptionsFromDatabase()
}
+50 -6
View File
@@ -3,6 +3,7 @@ package model
import (
"errors"
"fmt"
"math"
"strconv"
"strings"
"sync"
@@ -229,12 +230,13 @@ type SubscriptionOrder struct {
PlanId int `json:"plan_id" gorm:"index"`
Money float64 `json:"money"`
TradeNo string `json:"trade_no" gorm:"unique;type:varchar(255);index"`
PaymentMethod string `json:"payment_method" gorm:"type:varchar(50)"`
PaymentProvider string `json:"payment_provider" gorm:"type:varchar(50);default:''"`
Status string `json:"status"`
CreateTime int64 `json:"create_time"`
CompleteTime int64 `json:"complete_time"`
TradeNo string `json:"trade_no" gorm:"unique;type:varchar(255);index"`
PaymentMethod string `json:"payment_method" gorm:"type:varchar(50)"`
PaymentProvider string `json:"payment_provider" gorm:"type:varchar(50);default:''"`
PaymentCredentialRevisionID int `json:"-" gorm:"not null;default:0"`
Status string `json:"status"`
CreateTime int64 `json:"create_time"`
CompleteTime int64 `json:"complete_time"`
ProviderPayload string `json:"provider_payload" gorm:"type:text"`
}
@@ -1602,3 +1604,45 @@ func PostConsumeUserSubscriptionDelta(userSubscriptionId int, delta int64) error
return tx.Save(&sub).Error
})
}
// SettleUserSubscriptionDelta applies a post-request settlement delta and
// returns the amount actually applied to AmountUsed. Unlike
// PostConsumeUserSubscriptionDelta, which refuses overruns during reservation,
// a positive delta that exceeds the remaining allowance fills the subscription
// to AmountTotal and logs the uncovered part so subsequent requests do not keep
// passing small pre-consumes on an unexhausted plan.
func SettleUserSubscriptionDelta(userSubscriptionId int, delta int64) (applied int64, err error) {
if userSubscriptionId <= 0 {
return 0, errors.New("invalid userSubscriptionId")
}
if delta == 0 {
return 0, nil
}
err = DB.Transaction(func(tx *gorm.DB) error {
var sub UserSubscription
if err := lockForUpdate(tx).
Where("id = ?", userSubscriptionId).
First(&sub).Error; err != nil {
return err
}
charge := delta
if charge > 0 {
limit := int64(math.MaxInt64)
if sub.AmountTotal > 0 {
limit = sub.AmountTotal
}
charge = min(charge, max(limit-max(sub.AmountUsed, 0), 0))
}
newUsed := max(sub.AmountUsed+charge, 0)
applied = newUsed - sub.AmountUsed
sub.AmountUsed = newUsed
return tx.Save(&sub).Error
})
if err != nil {
return 0, err
}
if delta > 0 && applied < delta {
common.SysLog(common.LogText("subscription %d exhausted at settlement, %d quota of the final delta uncovered", userSubscriptionId, delta-applied))
}
return applied, nil
}
+1 -1
View File
@@ -14,7 +14,7 @@ type SupportTicketCategory string
func (category SupportTicketCategory) Valid() bool {
switch category {
case "api_error", "account", "payment", "feature_request", "other":
case "api_error", "account", "payment", "feature_request", "report", "other":
return true
default:
return false
+17 -6
View File
@@ -420,10 +420,19 @@ func TaskGetAllTasks(startIdx int, num int, queryParams SyncTaskQueryParams) []*
return tasks
}
// unfinishedTasks keeps tasks whose status is neither FAILURE nor SUCCESS.
// It writes the condition as the ranges around the two terminal statuses
// (FAILURE sorts before SUCCESS), so the database reads only unfinished rows
// from the status index instead of scanning every finished task.
func unfinishedTasks(tx *gorm.DB) *gorm.DB {
return tx.Where("status < ? OR (status > ? AND status < ?) OR status > ?",
TaskStatusFailure, TaskStatusFailure, TaskStatusSuccess, TaskStatusSuccess)
}
func GetTimedOutUnfinishedTasks(cutoffUnix int64, limit int) []*Task {
var tasks []*Task
err := DB.Where("status NOT IN ?", []string{TaskStatusFailure, TaskStatusSuccess, TaskStatusBillingPending}).
Where("submit_time < ?", cutoffUnix).
err := DB.Scopes(unfinishedTasks).
Where("status <> ? AND submit_time < ?", TaskStatusBillingPending, cutoffUnix).
Order("submit_time").
Limit(limit).
Find(&tasks).Error
@@ -435,9 +444,12 @@ func GetTimedOutUnfinishedTasks(cutoffUnix int64, limit int) []*Task {
func GetAllUnFinishSyncTasks(limit int) []*Task {
var tasks []*Task
var err error
// Upstream progress can reach 100% before the task enters a terminal state.
err = DB.Where("status NOT IN ?", []string{TaskStatusFailure, TaskStatusSuccess, TaskStatusBillingPending}).Limit(limit).Order("id").Find(&tasks).Error
err := DB.Scopes(unfinishedTasks).
Where("status <> ?", TaskStatusBillingPending).
Limit(limit).
Order("id").
Find(&tasks).Error
if err != nil {
return nil
}
@@ -473,8 +485,7 @@ func HasPendingWalletTaskSettlements() bool {
func HasUnfinishedSyncTasks() bool {
var id int64
err := DB.Model(&Task{}).
Where("status != ?", TaskStatusFailure).
Where("status != ?", TaskStatusSuccess).
Scopes(unfinishedTasks).
Limit(1).
Pluck("id", &id).Error
return err == nil && id != 0
+3 -2
View File
@@ -178,7 +178,7 @@ func TestUnfinishedTaskQueriesDatabaseMatrix(t *testing.T) {
assert.False(t, HasUnfinishedSyncTasks())
const cutoff int64 = 1_800_000_000
for _, status := range []TaskStatus{TaskStatusNotStart, TaskStatusSubmitted, TaskStatusQueued, TaskStatusInProgress, TaskStatusSuccess, TaskStatusFailure} {
for _, status := range []TaskStatus{"", TaskStatusNotStart, TaskStatusSubmitted, TaskStatusQueued, TaskStatusInProgress, TaskStatusUnknown, TaskStatusSuccess, TaskStatusFailure, TaskStatusBillingPending} {
for _, progress := range []string{"99%", "100%"} {
t.Run(string(status)+"/"+progress, func(t *testing.T) {
task := &Task{TaskID: "query_candidate", Status: status, Progress: progress, SubmitTime: cutoff - 1}
@@ -186,7 +186,8 @@ func TestUnfinishedTaskQueriesDatabaseMatrix(t *testing.T) {
t.Cleanup(func() { assert.NoError(t, db.Delete(task).Error) })
unfinished := status != TaskStatusSuccess && status != TaskStatusFailure
assert.Equal(t, unfinished, HasUnfinishedSyncTasks())
if unfinished {
assert.Equal(t, status == TaskStatusBillingPending, HasPendingWalletTaskSettlements())
if unfinished && status != TaskStatusBillingPending {
require.Len(t, GetAllUnFinishSyncTasks(1), 1)
assert.Equal(t, task.ID, GetAllUnFinishSyncTasks(1)[0].ID)
require.Len(t, GetTimedOutUnfinishedTasks(cutoff, 1), 1)
+11 -10
View File
@@ -12,16 +12,17 @@ import (
)
type TopUp struct {
Id int `json:"id"`
UserId int `json:"user_id" gorm:"index"`
Amount int64 `json:"amount"`
Money float64 `json:"money"`
TradeNo string `json:"trade_no" gorm:"unique;type:varchar(255);index"`
PaymentMethod string `json:"payment_method" gorm:"type:varchar(50)"`
PaymentProvider string `json:"payment_provider" gorm:"type:varchar(50);default:''"`
CreateTime int64 `json:"create_time"`
CompleteTime int64 `json:"complete_time"`
Status string `json:"status"`
Id int `json:"id"`
UserId int `json:"user_id" gorm:"index"`
Amount int64 `json:"amount"`
Money float64 `json:"money"`
TradeNo string `json:"trade_no" gorm:"unique;type:varchar(255);index"`
PaymentMethod string `json:"payment_method" gorm:"type:varchar(50)"`
PaymentProvider string `json:"payment_provider" gorm:"type:varchar(50);default:''"`
PaymentCredentialRevisionID int `json:"-" gorm:"not null;default:0"`
CreateTime int64 `json:"create_time"`
CompleteTime int64 `json:"complete_time"`
Status string `json:"status"`
}
const (
+4 -2
View File
@@ -8,6 +8,7 @@ import (
"net/url"
"strings"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/relay/channel"
"github.com/QuantumNous/new-api/relay/channel/claude"
@@ -423,12 +424,13 @@ func (a *Adaptor) resolve(c *gin.Context, info *relaycommon.RelayInfo) error {
func incomingRequestPath(c *gin.Context, info *relaycommon.RelayInfo) string {
if c != nil && c.Request != nil && c.Request.URL != nil {
return c.Request.URL.Path
return common.NormalizeRelayPath(c.Request.URL.Path)
}
if info == nil {
return ""
}
return strings.Split(info.RequestURLPath, "?")[0]
path, _, _ := strings.Cut(info.RequestURLPath, "?")
return common.NormalizeRelayPath(path)
}
func (a *Adaptor) routeURL(info *relaycommon.RelayInfo) (string, error) {
+4 -1
View File
@@ -284,6 +284,7 @@ func awsStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, a *Adaptor) (
}
events := stream.Events()
started := false
streamLoop:
for {
select {
@@ -302,8 +303,10 @@ streamLoop:
info.SetFirstResponseTime()
respErr := claude.HandleStreamResponseData(c, info, claudeInfo, string(v.Value.Bytes))
if respErr != nil {
return respErr, nil
usage, err := claude.HandleStartedStreamError(c, info, claudeInfo, started, respErr)
return err, usage
}
started = true
case *bedrockruntimeTypes.UnknownUnionMember:
fmt.Println(common.LogText("unknown tag: %v", v.Tag))
return types.NewError(errors.New("unknown response type"), types.ErrorCodeInvalidRequest), nil
+57 -29
View File
@@ -273,34 +273,7 @@ func recordClaudeServerToolUse(info *relaycommon.RelayInfo, serverToolUse *dto.C
}
func HandleStreamFinalResponse(c *gin.Context, info *relaycommon.RelayInfo, claudeInfo *ClaudeResponseInfo) {
// Claude input_tokens excludes cache reads and writes, so a fully cached
// prompt reports zero input; the prompt is uncounted only when the total
// with cache is zero as well. Zero output is uncounted only when content
// was streamed, so a refusal before any output keeps its zeros.
missingInputUsage := buildOpenAIStyleUsageFromClaudeUsage(claudeInfo.Usage).PromptTokens == 0
missingOutputUsage := claudeInfo.Usage.CompletionTokens == 0 && claudeInfo.ResponseText.Len() > 0
if missingInputUsage || missingOutputUsage || !claudeInfo.Done {
if common.DebugEnabled {
common.SysLog(common.LogText("claude response usage is not complete, maybe upstream error"))
}
// 只补缺失字段,不整份覆盖——保留 message_start 已拿到的 cache 字段
fallback := service.ResponseText2Usage(c, claudeInfo.ResponseText.String(), info.UpstreamModelName, info.GetEstimatePromptTokens())
// Each tool_use block costs about 40 output tokens beyond its name and JSON
// input (measured on Claude Haiku 4.5 and Sonnet 5 agent turns).
fallback.CompletionTokens += claudeInfo.ToolUseCount * 40
if missingOutputUsage ||
(!claudeInfo.Done && fallback.CompletionTokens > claudeInfo.Usage.CompletionTokens) {
claudeInfo.Usage.CompletionTokens = fallback.CompletionTokens
}
if missingInputUsage {
claudeInfo.Usage.PromptTokens = fallback.PromptTokens
}
claudeInfo.Usage.TotalTokens = claudeInfo.Usage.PromptTokens + claudeInfo.Usage.CompletionTokens
}
if claudeInfo.Usage != nil {
claudeInfo.Usage.UsageSemantic = "anthropic"
}
relayconvert.FinalizeClaudeStreamBillingUsage(claudeInfo)
completeClaudeStreamUsage(c, info, claudeInfo)
if info.RelayFormat == types.RelayFormatClaude {
//
@@ -331,6 +304,58 @@ func HandleStreamFinalResponse(c *gin.Context, info *relaycommon.RelayInfo, clau
}
}
// HandleStartedStreamError settles a stream that fails after events have
// reached the client. A retry would splice a second message into the same
// response, so the failure ends this stream without one: with output
// delivered, the client gets the error event here and the output is billed;
// with none, the error goes back to the relay, which sends it and refunds.
func HandleStartedStreamError(c *gin.Context, info *relaycommon.RelayInfo, claudeInfo *ClaudeResponseInfo, started bool, streamErr *types.NewAPIError) (*dto.Usage, *types.NewAPIError) {
if !started {
return nil, streamErr
}
if claudeInfo.ResponseText.Len() == 0 {
types.ErrOptionWithSkipRetry()(streamErr)
return nil, streamErr
}
common.SetContextKey(c, constant.ContextKeyResponseStreamStatus, info.StreamStatus)
helper.StreamErrorData(c, info.RelayFormat, streamErr)
completeClaudeStreamUsage(c, info, claudeInfo)
return claudeInfo.Usage, nil
}
// completeClaudeStreamUsage fills the usage a stream left unreported from the
// streamed content and finalizes its billing usage.
func completeClaudeStreamUsage(c *gin.Context, info *relaycommon.RelayInfo, claudeInfo *ClaudeResponseInfo) {
// Claude input_tokens excludes cache reads and writes, so a fully cached
// prompt reports zero input; the prompt is uncounted only when the total
// with cache is zero as well. Zero output is uncounted only when content
// was streamed, so a refusal before any output keeps its zeros.
missingInputUsage := buildOpenAIStyleUsageFromClaudeUsage(claudeInfo.Usage).PromptTokens == 0
missingOutputUsage := claudeInfo.Usage.CompletionTokens == 0 && claudeInfo.ResponseText.Len() > 0
if missingInputUsage || missingOutputUsage || !claudeInfo.Done {
if common.DebugEnabled {
common.SysLog(common.LogText("claude response usage is not complete, maybe upstream error"))
}
// 只补缺失字段,不整份覆盖——保留 message_start 已拿到的 cache 字段
fallback := service.ResponseText2Usage(c, claudeInfo.ResponseText.String(), info.UpstreamModelName, info.GetEstimatePromptTokens())
// Each tool_use block costs about 40 output tokens beyond its name and JSON
// input (measured on Claude Haiku 4.5 and Sonnet 5 agent turns).
fallback.CompletionTokens += claudeInfo.ToolUseCount * 40
if missingOutputUsage ||
(!claudeInfo.Done && fallback.CompletionTokens > claudeInfo.Usage.CompletionTokens) {
claudeInfo.Usage.CompletionTokens = fallback.CompletionTokens
}
if missingInputUsage {
claudeInfo.Usage.PromptTokens = fallback.PromptTokens
}
claudeInfo.Usage.TotalTokens = claudeInfo.Usage.PromptTokens + claudeInfo.Usage.CompletionTokens
}
if claudeInfo.Usage != nil {
claudeInfo.Usage.UsageSemantic = "anthropic"
}
relayconvert.FinalizeClaudeStreamBillingUsage(claudeInfo)
}
func ClaudeStreamHandler(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (*dto.Usage, *types.NewAPIError) {
claudeInfo := &ClaudeResponseInfo{
ResponseId: helper.GetResponseID(c),
@@ -340,15 +365,18 @@ func ClaudeStreamHandler(c *gin.Context, resp *http.Response, info *relaycommon.
Usage: &dto.Usage{},
}
var err *types.NewAPIError
started := false
helper.StreamScannerHandler(c, resp, info, func(data string, sr *helper.StreamResult) {
err = HandleStreamResponseData(c, info, claudeInfo, data)
if err != nil {
sr.Stop(err)
return
}
started = true
})
info.StreamStatus.RequireTerminal()
if err != nil {
return nil, err
return HandleStartedStreamError(c, info, claudeInfo, started, err)
}
HandleStreamFinalResponse(c, info, claudeInfo)
+69
View File
@@ -2,6 +2,7 @@ package claude
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
@@ -65,6 +66,74 @@ func TestClaudeStreamFinalUsageEstimatesOnlyUncountedUsage(t *testing.T) {
}
}
func TestClaudeStreamErrorRetriesOnlyBeforeTheClientGotEvents(t *testing.T) {
gin.SetMode(gin.TestMode)
previousTimeout := constant.StreamingTimeout
constant.StreamingTimeout = 30
t.Cleanup(func() { constant.StreamingTimeout = previousTimeout })
start := `{"type":"message_start","message":{"id":"msg_1","model":"claude-opus-4-8","usage":{"input_tokens":1000,"output_tokens":1}}}`
thinking := `{"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"hello"}}`
overloaded := `{"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}`
for _, tc := range []struct {
name string
format types.RelayFormat
events []string
wantErr bool
wantRetry bool
wantInput int
wantOutput int
wantBody []string
}{
{name: "error before any event may retry", format: types.RelayFormatClaude, events: []string{overloaded}, wantErr: true, wantRetry: true},
{name: "error after message_start ends the stream unbilled", format: types.RelayFormatClaude, events: []string{start, overloaded}, wantErr: true},
{name: "error after output reaches the client and bills it", format: types.RelayFormatClaude, events: []string{start, thinking, overloaded}, wantInput: 1000, wantOutput: 2, wantBody: []string{"event: error\n", `"type":"overloaded_error"`}},
{name: "converted chat stream gets the error and bills the output", format: types.RelayFormatOpenAI, events: []string{start, thinking, overloaded}, wantInput: 1000, wantOutput: 2, wantBody: []string{`"error":`, `"overloaded_error"`, "data: [DONE]"}},
{name: "converted responses stream bills the output before response.failed", format: types.RelayFormatOpenAIResponses, events: []string{start, thinking, overloaded}, wantInput: 1000, wantOutput: 2, wantBody: []string{"event: response.failed\n"}},
{name: "converted responses stream failing before output is free", format: types.RelayFormatOpenAIResponses, events: []string{start, overloaded}, wantBody: []string{"event: response.failed\n"}},
} {
t.Run(tc.name, func(t *testing.T) {
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil)
info := &relaycommon.RelayInfo{RelayFormat: tc.format, IsStream: true, ChannelMeta: &relaycommon.ChannelMeta{UpstreamModelName: "claude-opus-4-8"}}
info.SetEstimatePromptTokens(1200)
var body strings.Builder
for _, event := range tc.events {
body.WriteString("data: " + event + "\n\n")
}
resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, Body: io.NopCloser(strings.NewReader(body.String()))}
handler := ClaudeStreamHandler
if tc.format == types.RelayFormatOpenAIResponses {
handler = ClaudeResponsesStreamHandler
}
usage, apiErr := handler(c, resp, info)
if tc.wantErr {
require.NotNil(t, apiErr)
assert.Nil(t, usage, "a failure without output is refunded")
assert.Equal(t, tc.wantRetry, !types.IsSkipRetryError(apiErr))
assert.NotContains(t, recorder.Body.String(), "Overloaded", "the relay sends the error once")
return
}
require.Nil(t, apiErr)
for _, want := range tc.wantBody {
assert.Contains(t, recorder.Body.String(), want)
}
assert.Equal(t, 1, strings.Count(recorder.Body.String(), tc.wantBody[0]), "the failure is sent once")
assert.True(t, info.StreamStatus.ResponseFailed())
assert.Equal(t, tc.wantInput, usage.PromptTokens)
assert.Equal(t, tc.wantOutput, usage.CompletionTokens)
if tc.wantOutput == 0 {
return
}
canonical, ok := usage.BillingUsage.CanonicalUsage()
require.True(t, ok)
assert.Equal(t, tc.wantOutput, canonical.CompletionTokens, "settlement must bill the delivered output")
})
}
}
func TestResponseOpenAI2ClaudeToolUseInputIsObject(t *testing.T) {
tests := []struct {
name string
+9
View File
@@ -6,6 +6,7 @@ import (
"strings"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/logger"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/relay/helper"
@@ -78,6 +79,8 @@ func ClaudeResponsesStreamHandler(c *gin.Context, resp *http.Response, info *rel
return true
}
}
info.StreamStatus.MarkFailed("server_error", "", 0)
common.SetContextKey(c, constant.ContextKeyResponseStreamStatus, info.StreamStatus)
streamFailed = true
return true
}
@@ -162,6 +165,12 @@ func ClaudeResponsesStreamHandler(c *gin.Context, resp *http.Response, info *rel
return nil, streamErr
}
if streamFailed {
// The client received response.failed: output it got before the failure
// is billed, and a failure before any output is free.
if claudeInfo.ResponseText.Len() == 0 {
return &dto.Usage{}, nil
}
completeClaudeStreamUsage(c, info, claudeInfo)
return claudeInfo.Usage, nil
}
+44 -21
View File
@@ -420,6 +420,8 @@ func GeminiChatStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *
id := helper.GetResponseID(c)
createAt := common.GetTimestamp()
finishReason := constant.FinishReasonStop
sawToolCall := false
finishEmitted := false
toolCallIndexByChoice := make(map[int]map[string]int)
nextToolCallIndexByChoice := make(map[int]int)
@@ -429,18 +431,25 @@ func GeminiChatStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *
response.Id = id
response.Created = createAt
response.Model = info.UpstreamModelName
if response.IsToolCall() {
finishReason = constant.FinishReasonToolCalls
if info.RelayFormat == types.RelayFormatClaude {
for choiceIdx := range response.Choices {
response.Choices[choiceIdx].FinishReason = nil
}
}
}
hasUpstreamFinish := isStop
upstreamNonStopReason := ""
hasDelta := false
for choiceIdx := range response.Choices {
choiceKey := response.Choices[choiceIdx].Index
for toolIdx := range response.Choices[choiceIdx].Delta.ToolCalls {
tool := &response.Choices[choiceIdx].Delta.ToolCalls[toolIdx]
choice := &response.Choices[choiceIdx]
if choice.FinishReason != nil && *choice.FinishReason != "" {
hasUpstreamFinish = true
if upstreamNonStopReason == "" {
upstreamNonStopReason = *choice.FinishReason
}
choice.FinishReason = nil
}
choiceKey := choice.Index
if len(choice.Delta.ToolCalls) > 0 {
sawToolCall = true
}
for toolIdx := range choice.Delta.ToolCalls {
tool := &choice.Delta.ToolCalls[toolIdx]
if tool.ID == "" {
continue
}
@@ -458,10 +467,22 @@ func GeminiChatStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *
m[tool.ID] = idx
tool.SetIndex(idx)
}
if choice.Delta.GetContentString() != "" ||
choice.Delta.GetReasoningContent() != "" ||
len(choice.Delta.ToolCalls) > 0 ||
len(choice.Delta.Annotations) > 0 {
hasDelta = true
}
}
if upstreamNonStopReason != "" {
finishReason = upstreamNonStopReason
} else if sawToolCall && finishReason == constant.FinishReasonStop {
finishReason = constant.FinishReasonToolCalls
}
logger.LogDebug(c, "info.SendResponseCount = %d", info.SendResponseCount)
if info.SendResponseCount == 0 {
if info.SendResponseCount == 0 && (hasDelta || hasUpstreamFinish) {
// send first response
emptyResponse := helper.GenerateStartEmptyResponse(id, createAt, info.UpstreamModelName, nil)
// Claude message_start is emitted from this first OpenAI chunk.
@@ -477,16 +498,11 @@ func GeminiChatStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *
}
emptyResponse.Choices[0].Delta.ToolCalls = copiedToolCalls
}
finishReason = constant.FinishReasonToolCalls
err := handleStream(c, info, emptyResponse)
if err != nil {
logger.LogError(c, err.Error())
}
response.ClearToolCalls()
if response.IsFinished() {
response.Choices[0].FinishReason = nil
}
} else {
err := handleStream(c, info, emptyResponse)
if err != nil {
@@ -495,13 +511,16 @@ func GeminiChatStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *
}
}
err := handleStream(c, info, response)
if err != nil {
logger.LogError(c, err.Error())
if hasDelta && !finishEmitted {
err := handleStream(c, info, response)
if err != nil {
logger.LogError(c, err.Error())
}
}
if isStop {
if hasUpstreamFinish && !finishEmitted {
if info.RelayFormat != types.RelayFormatClaude {
_ = handleStream(c, info, helper.GenerateStopResponse(id, createAt, info.UpstreamModelName, finishReason))
finishEmitted = true
}
}
return true
@@ -511,6 +530,10 @@ func GeminiChatStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *
return usage, err
}
if info.RelayFormat != types.RelayFormatClaude && info.SendResponseCount > 0 && !finishEmitted && !isGeminiDownstreamStop(c, info) {
_ = handleStream(c, info, helper.GenerateStopResponse(id, createAt, info.UpstreamModelName, finishReason))
}
response := helper.GenerateFinalUsageResponse(id, createAt, info.UpstreamModelName, *usage)
if info.RelayFormat == types.RelayFormatClaude && info.ClaudeConvertInfo != nil && !info.ClaudeConvertInfo.Done {
response = helper.GenerateStopResponse(id, createAt, info.UpstreamModelName, finishReason)
+57
View File
@@ -1,6 +1,8 @@
package openai
import (
"bytes"
"encoding/json"
"fmt"
"strings"
@@ -19,6 +21,61 @@ import (
"github.com/gin-gonic/gin"
)
type openAIStreamOutputProbe struct {
Choices []struct {
Text json.RawMessage `json:"text"`
Delta struct {
Content json.RawMessage `json:"content"`
ReasoningContent json.RawMessage `json:"reasoning_content"`
Reasoning json.RawMessage `json:"reasoning"`
ReasoningDetails json.RawMessage `json:"reasoning_details"`
Refusal json.RawMessage `json:"refusal"`
ToolCalls json.RawMessage `json:"tool_calls"`
FunctionCall json.RawMessage `json:"function_call"`
Audio json.RawMessage `json:"audio"`
Annotations json.RawMessage `json:"annotations"`
Images json.RawMessage `json:"images"`
} `json:"delta"`
} `json:"choices"`
}
func hasNonEmptyJSONValue(raw json.RawMessage) bool {
b := bytes.TrimSpace(raw)
if len(b) == 0 || bytes.Equal(b, []byte("null")) || bytes.Equal(b, []byte(`""`)) {
return false
}
if len(b) >= 2 && ((b[0] == '[' && b[len(b)-1] == ']') || (b[0] == '{' && b[len(b)-1] == '}')) {
return len(bytes.TrimSpace(b[1:len(b)-1])) > 0
}
return true
}
// hasOpenAIStreamOutput reports whether an OpenAI Chat Completions or
// Completions SSE data payload carries generated output rather than role-only,
// empty-content, keepalive, or usage-only metadata.
func hasOpenAIStreamOutput(data string) bool {
var chunk openAIStreamOutputProbe
if err := common.UnmarshalJsonStr(data, &chunk); err != nil {
return false
}
for _, choice := range chunk.Choices {
if hasNonEmptyJSONValue(choice.Text) ||
hasNonEmptyJSONValue(choice.Delta.Content) ||
hasNonEmptyJSONValue(choice.Delta.ReasoningContent) ||
hasNonEmptyJSONValue(choice.Delta.Reasoning) ||
hasNonEmptyJSONValue(choice.Delta.ReasoningDetails) ||
hasNonEmptyJSONValue(choice.Delta.Refusal) ||
hasNonEmptyJSONValue(choice.Delta.ToolCalls) ||
hasNonEmptyJSONValue(choice.Delta.FunctionCall) ||
hasNonEmptyJSONValue(choice.Delta.Audio) ||
hasNonEmptyJSONValue(choice.Delta.Annotations) ||
hasNonEmptyJSONValue(choice.Delta.Images) {
return true
}
}
return false
}
// 辅助函数
func HandleStreamFormat(c *gin.Context, info *relaycommon.RelayInfo, data string, forceFormat bool, thinkToContent bool) error {
switch info.RelayFormat {
+1 -1
View File
@@ -142,7 +142,7 @@ func OaiStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.Re
sr.Error(err)
}
}
})
}, helper.WithFirstResponsePredicate(hasOpenAIStreamOutput))
info.StreamStatus.RequireTerminal()
+1 -1
View File
@@ -179,7 +179,7 @@ func OaiChatToResponsesStreamHandler(c *gin.Context, info *relaycommon.RelayInfo
return
}
}
})
}, helper.WithFirstResponsePredicate(hasOpenAIStreamOutput))
if streamErr != nil {
return nil, streamErr
@@ -0,0 +1,203 @@
package openai
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/QuantumNous/new-api/constant"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/relaykit/dto"
"github.com/QuantumNous/new-api/relaykit/types"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestHasOpenAIStreamOutput(t *testing.T) {
t.Parallel()
tests := []struct {
name string
data string
want bool
}{
{
name: "role and empty content keepalive chunk",
data: `{"id":"chatcmpl-1","object":"chat.completion.chunk","created":1700000005,"model":"gpt-4o","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]}`,
want: false,
},
{
name: "role only chunk",
data: `{"id":"chatcmpl-1","object":"chat.completion.chunk","created":1700000000,"model":"gpt-4o","choices":[{"index":0,"delta":{"role":"assistant"}}]}`,
want: false,
},
{
name: "null content and empty tool calls",
data: `{"choices":[{"index":0,"delta":{"role":"assistant","content":null,"reasoning_content":null,"tool_calls":[]},"finish_reason":null}]}`,
want: false,
},
{
name: "usage only chunk with empty choices",
data: `{"id":"chatcmpl-1","choices":[],"usage":{"prompt_tokens":100,"completion_tokens":0,"total_tokens":100}}`,
want: false,
},
{
name: "zero output content filter terminal chunk",
data: `{"choices":[{"index":0,"delta":{"content":""},"finish_reason":"content_filter"}],"usage":{"prompt_tokens":100,"completion_tokens":0,"total_tokens":100}}`,
want: false,
},
{
name: "legacy completions empty text",
data: `{"choices":[{"index":0,"text":"","finish_reason":null}]}`,
want: false,
},
{
name: "inline error object",
data: `{"error":{"message":"upstream failed","type":"server_error"}}`,
want: false,
},
{
name: "non-json payload",
data: `not-json`,
want: false,
},
{
name: "text content token",
data: `{"choices":[{"index":0,"delta":{"content":"Hello"}}]}`,
want: true,
},
{
name: "whitespace content token",
data: `{"choices":[{"index":0,"delta":{"content":" "}}]}`,
want: true,
},
{
name: "reasoning_content token",
data: `{"choices":[{"index":0,"delta":{"reasoning_content":"The"}}]}`,
want: true,
},
{
name: "reasoning alias token",
data: `{"choices":[{"index":0,"delta":{"reasoning":"Step 1"}}]}`,
want: true,
},
{
name: "reasoning_details array",
data: `{"choices":[{"index":0,"delta":{"reasoning_details":[{"type":"reasoning.text","text":"step"}]}}]}`,
want: true,
},
{
name: "refusal token",
data: `{"choices":[{"index":0,"delta":{"refusal":"I cannot help with that."}}]}`,
want: true,
},
{
name: "tool_calls chunk",
data: `{"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_1","type":"function","function":{"name":"get_weather","arguments":""}}]}}]}`,
want: true,
},
{
name: "legacy function_call chunk",
data: `{"choices":[{"index":0,"delta":{"function_call":{"name":"get_weather","arguments":""}}}]}`,
want: true,
},
{
name: "audio chunk",
data: `{"choices":[{"index":0,"delta":{"audio":{"id":"audio_1","data":"//uQ"}}}]}`,
want: true,
},
{
name: "annotations chunk",
data: `{"choices":[{"index":0,"delta":{"annotations":[{"type":"url_citation"}]}}]}`,
want: true,
},
{
name: "multimodal content array",
data: `{"choices":[{"index":0,"delta":{"content":[{"type":"text","text":"Hi"}]}}]}`,
want: true,
},
{
name: "legacy completions non-empty text",
data: `{"choices":[{"index":0,"text":"Hello"}]}`,
want: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
assert.Equal(t, tt.want, hasOpenAIStreamOutput(tt.data))
})
}
}
func TestOaiStreamHandler_FirstResponseTimeSkipsEmptyChunks(t *testing.T) {
oldTimeout := constant.StreamingTimeout
constant.StreamingTimeout = 30
t.Cleanup(func() { constant.StreamingTimeout = oldTimeout })
pr, pw := io.Pipe()
go func() {
defer pw.Close()
_, _ = fmt.Fprint(pw, "data: {\"id\":\"chatcmpl-1\",\"object\":\"chat.completion.chunk\",\"created\":1700000005,\"model\":\"gpt-4o\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":\"\"},\"finish_reason\":null}]}\n\n")
time.Sleep(80 * time.Millisecond)
_, _ = fmt.Fprint(pw, "data: {\"id\":\"chatcmpl-1\",\"object\":\"chat.completion.chunk\",\"created\":1700000000,\"model\":\"gpt-4o\",\"choices\":[{\"index\":0,\"delta\":{\"reasoning_content\":\"Think\"},\"finish_reason\":null}]}\n\n")
_, _ = fmt.Fprint(pw, "data: {\"id\":\"chatcmpl-1\",\"object\":\"chat.completion.chunk\",\"created\":1700000000,\"model\":\"gpt-4o\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"Hello\"},\"finish_reason\":null}]}\n\n")
_, _ = fmt.Fprint(pw, "data: {\"id\":\"chatcmpl-1\",\"object\":\"chat.completion.chunk\",\"created\":1700000000,\"model\":\"gpt-4o\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}],\"usage\":{\"prompt_tokens\":100,\"completion_tokens\":10,\"total_tokens\":110}}\n\n")
_, _ = fmt.Fprint(pw, "data: [DONE]\n\n")
}()
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
stream := true
info, err := relaycommon.GenRelayInfo(c, types.RelayFormatOpenAI, &dto.GeneralOpenAIRequest{Model: "gpt-4o", Stream: &stream}, nil)
require.NoError(t, err)
info.ChannelMeta = &relaycommon.ChannelMeta{UpstreamModelName: "gpt-4o"}
info.DisablePing = true
usage, apiErr := OaiStreamHandler(c, info, &http.Response{Body: pr})
require.Nil(t, apiErr)
require.NotNil(t, usage)
assert.Equal(t, 100, usage.PromptTokens)
assert.Equal(t, 10, usage.CompletionTokens)
assert.True(t, info.HasSendResponse())
assert.GreaterOrEqual(t, info.FirstResponseTime.Sub(info.StartTime), 70*time.Millisecond)
assert.Contains(t, recorder.Body.String(), `"reasoning_content":"Think"`)
assert.Contains(t, recorder.Body.String(), `"content":"Hello"`)
}
func TestOaiStreamHandler_ZeroOutputDoesNotSetFirstResponseTime(t *testing.T) {
oldTimeout := constant.StreamingTimeout
constant.StreamingTimeout = 30
t.Cleanup(func() { constant.StreamingTimeout = oldTimeout })
body := strings.Join([]string{
`data: {"id":"chatcmpl-2","object":"chat.completion.chunk","created":1700000005,"model":"gpt-4o-mini","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]}`,
`data: {"id":"chatcmpl-2","object":"chat.completion.chunk","created":1700000000,"model":"gpt-4o-mini","choices":[{"index":0,"delta":{"content":""},"finish_reason":"content_filter"}],"usage":{"prompt_tokens":100,"completion_tokens":0,"total_tokens":100}}`,
`data: [DONE]`,
``,
}, "\n\n")
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
stream := true
info, err := relaycommon.GenRelayInfo(c, types.RelayFormatOpenAI, &dto.GeneralOpenAIRequest{Model: "gpt-4o-mini", Stream: &stream}, nil)
require.NoError(t, err)
info.ChannelMeta = &relaycommon.ChannelMeta{UpstreamModelName: "gpt-4o-mini"}
info.DisablePing = true
usage, apiErr := OaiStreamHandler(c, info, &http.Response{Body: io.NopCloser(strings.NewReader(body))})
require.Nil(t, apiErr)
require.NotNil(t, usage)
assert.Equal(t, 0, usage.CompletionTokens)
assert.False(t, info.HasSendResponse())
}
+6 -4
View File
@@ -207,7 +207,7 @@ func (a *Adaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, request
}
ctx := c.Request.Context()
input := jsplugin.ConvertInput{Path: c.Request.URL.Path, Model: info.UpstreamModelName, Stream: info.IsStream}
input := jsplugin.ConvertInput{Path: common.NormalizeRelayPath(c.Request.URL.Path), Model: info.UpstreamModelName, Stream: info.IsStream}
// files are the client's uploaded files by reference, nil for a JSON
// request.
var files map[string]*multipart.FileHeader
@@ -526,7 +526,9 @@ func (a *Adaptor) bind(c *gin.Context, info *relaycommon.RelayInfo) error {
if c.Request != nil && c.Request.URL != nil {
path = c.Request.URL.Path
}
route, ok := a.plugin.Meta.ChannelRelayRoute(info.ChannelOtherSettings.PluginRoutes, strings.Split(path, "?")[0], info.OriginModelName)
path, _, _ = strings.Cut(path, "?")
path = common.NormalizeRelayPath(path)
route, ok := a.plugin.Meta.ChannelRelayRoute(info.ChannelOtherSettings.PluginRoutes, path, info.OriginModelName)
if !ok {
return fmt.Errorf("plugin %s has no relay route for %s and model %s", a.plugin.Meta.Key, path, info.OriginModelName)
}
@@ -594,7 +596,7 @@ func (a *Adaptor) credentialContext(info *relaycommon.RelayInfo) jsplugin.Creden
func (a *Adaptor) hookContext(c *gin.Context, info *relaycommon.RelayInfo) jsplugin.HookContext {
hookCtx := jsplugin.HookContext{BaseURL: info.ChannelBaseUrl, Config: a.config, Token: a.token}
if c != nil && c.Request != nil && c.Request.URL != nil {
hookCtx.Path = c.Request.URL.Path
hookCtx.Path = common.NormalizeRelayPath(c.Request.URL.Path)
}
return hookCtx
}
@@ -706,7 +708,7 @@ func (a *Adaptor) prepare(c *gin.Context, info *relaycommon.RelayInfo, body []by
}
}
prepared, err := a.plugin.CallPrepareRequest(c.Request.Context(), a.hookContext(c, info), jsplugin.PrepareInput{
Path: c.Request.URL.Path,
Path: common.NormalizeRelayPath(c.Request.URL.Path),
UpstreamPath: upstreamPath,
Model: info.UpstreamModelName,
Stream: info.IsStream,
+5 -1
View File
@@ -350,7 +350,7 @@ func (info *RelayInfo) InitChannelMeta(c *gin.Context) {
if (channelType == constant.ChannelTypeAdvancedCustom || providerPlugin) &&
!channelMeta.ChannelSetting.PassThroughBodyEnabled &&
c.Request != nil && c.Request.URL != nil {
route, matched := channelMeta.ChannelOtherSettings.AdvancedCustom.MatchPathForModel(c.Request.URL.Path, info.OriginModelName)
route, matched := channelMeta.ChannelOtherSettings.AdvancedCustom.MatchPathForModel(common.NormalizeRelayPath(c.Request.URL.Path), info.OriginModelName)
if matched && route.PassThroughBodyEnabled {
channelMeta.ChannelSetting.PassThroughBodyEnabled = true
}
@@ -1030,6 +1030,10 @@ func (info *RelayInfo) ConvOptions() *convmeta.Options {
return options
}
func (info *RelayInfo) IsFirstResponsePending() bool {
return info != nil && info.isFirstResponse
}
func (info *RelayInfo) SetFirstResponseTime() {
if info.isFirstResponse {
info.FirstResponseTime = time.Now()
+21
View File
@@ -9,7 +9,9 @@ import (
"time"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/logger"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/relaykit/dto"
"github.com/QuantumNous/new-api/relaykit/types"
@@ -296,6 +298,25 @@ func Done(c *gin.Context) {
_ = StringData(c, "[DONE]")
}
// StreamErrorData ends a stream whose response has already started with an
// error event in the client's protocol, and records the failure on the
// response stream status.
func StreamErrorData(c *gin.Context, format types.RelayFormat, apiError *types.NewAPIError) {
status, _ := common.GetContextKeyType[*relaycommon.StreamStatus](c, constant.ContextKeyResponseStreamStatus)
if status == nil {
status = relaycommon.NewStreamStatus()
common.SetContextKey(c, constant.ContextKeyResponseStreamStatus, status)
}
status.MarkFailed(string(apiError.GetErrorCode()), string(apiError.GetErrorType()), apiError.StatusCode)
upstreamURLs := common.UpstreamAddresses(c)
if format == types.RelayFormatClaude {
_ = ClaudeData(c, dto.ClaudeResponse{Type: "error", Error: apiError.ToClaudeError(upstreamURLs...)})
return
}
_ = ObjectData(c, gin.H{"error": apiError.ToOpenAIError(upstreamURLs...)})
Done(c)
}
func WssString(c *gin.Context, ws *websocket.Conn, str string) error {
if ws == nil {
logger.LogError(c, common.LogText("websocket connection is nil"))
+27 -2
View File
@@ -117,12 +117,35 @@ func (w *streamResponseWriter) Unwrap() http.ResponseWriter {
return w.ResponseWriter
}
func StreamScannerHandler(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo, dataHandler func(data string, sr *StreamResult)) {
// StreamScannerOption customizes StreamScannerHandler behavior.
type StreamScannerOption func(*streamScannerConfig)
type streamScannerConfig struct {
isFirstResponse func(data string) bool
}
// WithFirstResponsePredicate delays info.SetFirstResponseTime until a
// non-[DONE] SSE data frame satisfies pred. A nil predicate preserves the
// default behavior of recording the first non-[DONE] data frame.
func WithFirstResponsePredicate(pred func(data string) bool) StreamScannerOption {
return func(cfg *streamScannerConfig) {
cfg.isFirstResponse = pred
}
}
func StreamScannerHandler(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo, dataHandler func(data string, sr *StreamResult), opts ...StreamScannerOption) {
if resp == nil || dataHandler == nil {
return
}
var cfg streamScannerConfig
for _, opt := range opts {
if opt != nil {
opt(&cfg)
}
}
// Finish the request keepalive before changing headers. The scanner owns
// subsequent ping and data writes through its shared write mutex.
if writer := keepAliveWriter(c); writer != nil {
@@ -307,7 +330,9 @@ func StreamScannerHandler(c *gin.Context, resp *http.Response, info *relaycommon
continue
}
if data != "[DONE]" {
info.SetFirstResponseTime()
if info.IsFirstResponsePending() && (cfg.isFirstResponse == nil || cfg.isFirstResponse(data)) {
info.SetFirstResponseTime()
}
info.ReceivedResponseCount++
select {
+64
View File
@@ -15,6 +15,8 @@ import (
"github.com/QuantumNous/new-api/constant"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/relaykit/dto"
"github.com/QuantumNous/new-api/relaykit/types"
"github.com/QuantumNous/new-api/setting/operation_setting"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
@@ -724,3 +726,65 @@ func TestSetEventStreamHeadersBoundsStreamWritesByBudget(t *testing.T) {
assert.False(t, recorder.deadlines[0].Before(before.Add(streamWriteTimeout+450*time.Second)))
assert.Contains(t, recorder.Body.String(), "data: AAAA")
}
func TestStreamScannerHandler_WithFirstResponsePredicate(t *testing.T) {
t.Parallel()
newPendingInfo := func(t *testing.T, c *gin.Context) *relaycommon.RelayInfo {
t.Helper()
stream := true
info, err := relaycommon.GenRelayInfo(c, types.RelayFormatOpenAI, &dto.GeneralOpenAIRequest{Model: "gpt-4o", Stream: &stream}, nil)
require.NoError(t, err)
return info
}
t.Run("delays first response until predicate matches and stops evaluating after latch", func(t *testing.T) {
t.Parallel()
pr, pw := io.Pipe()
go func() {
defer pw.Close()
_, _ = fmt.Fprint(pw, "data: empty-1\n\n")
time.Sleep(80 * time.Millisecond)
_, _ = fmt.Fprint(pw, "data: token-1\n\n")
_, _ = fmt.Fprint(pw, "data: token-2\n\n")
_, _ = fmt.Fprint(pw, "data: [DONE]\n\n")
}()
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
info := newPendingInfo(t, c)
resp := &http.Response{Body: pr}
var predCalls atomic.Int64
var received []string
StreamScannerHandler(c, resp, info, func(data string, _ *StreamResult) {
received = append(received, data)
}, WithFirstResponsePredicate(func(data string) bool {
predCalls.Add(1)
return strings.HasPrefix(data, "token-")
}))
assert.Equal(t, []string{"empty-1", "token-1", "token-2"}, received)
assert.Equal(t, int64(2), predCalls.Load(), "predicate should not be called after latching")
assert.True(t, info.HasSendResponse())
assert.GreaterOrEqual(t, info.FirstResponseTime.Sub(info.StartTime), 70*time.Millisecond)
})
t.Run("leaves first response unset when no chunk matches", func(t *testing.T) {
t.Parallel()
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
info := newPendingInfo(t, c)
resp := &http.Response{Body: io.NopCloser(strings.NewReader("data: empty-1\n\ndata: empty-2\n\ndata: [DONE]\n\n"))}
StreamScannerHandler(c, resp, info, func(string, *StreamResult) {}, WithFirstResponsePredicate(func(string) bool {
return false
}))
assert.False(t, info.HasSendResponse())
assert.True(t, info.IsFirstResponsePending())
assert.Equal(t, 2, info.ReceivedResponseCount)
})
}
@@ -227,9 +227,8 @@ func streamResponseGeminiChat2OpenAI(geminiResponse *dto.GeminiChatResponse) (*d
appended++
lastWasText = text
}
isTools := false
isThought := false
if candidate.FinishReason != nil {
if candidate.FinishReason != nil && *candidate.FinishReason != "" && *candidate.FinishReason != "FINISH_REASON_UNSPECIFIED" {
switch *candidate.FinishReason {
case "STOP":
choice.FinishReason = &types.FinishReasonStop
@@ -254,7 +253,6 @@ func streamResponseGeminiChat2OpenAI(geminiResponse *dto.GeminiChatResponse) (*d
content.WriteByte(')')
}
} else if part.FunctionCall != nil {
isTools = true
if call := geminiResponseToolCall(&part); call != nil {
call.SetIndex(len(choice.Delta.ToolCalls))
choice.Delta.ToolCalls = append(choice.Delta.ToolCalls, *call)
@@ -285,14 +283,13 @@ func streamResponseGeminiChat2OpenAI(geminiResponse *dto.GeminiChatResponse) (*d
}
var emittedParts []renderedGeminiPart
if isThought {
choice.Delta.SetReasoningContent(content.String())
} else {
if content.Len() > 0 {
choice.Delta.SetReasoningContent(content.String())
}
} else if content.Len() > 0 {
choice.Delta.SetContentString(content.String())
emittedParts = textParts
}
if isTools {
choice.FinishReason = &types.FinishReasonToolCalls
}
choice.Delta.Annotations = groundingAnnotationsToChat(candidate.GroundingMetadata, textParts, content.String())
choices = append(choices, choice)
contentParts = append(contentParts, emittedParts)
@@ -382,13 +379,6 @@ func (s *GeminiToChatStreamState) ConvertChunk(geminiResponse *dto.GeminiChatRes
if err != nil {
return nil, err
}
hasNonStopFinish := false
for _, candidate := range geminiResponse.Candidates {
if candidate.FinishReason != nil && *candidate.FinishReason != "" && *candidate.FinishReason != "STOP" {
hasNonStopFinish = true
break
}
}
response, isStop, contentParts := streamResponseGeminiChat2OpenAI(geminiResponse)
if response == nil {
return nil, nil
@@ -397,12 +387,23 @@ func (s *GeminiToChatStreamState) ConvertChunk(geminiResponse *dto.GeminiChatRes
response.Created = s.created
response.Model = model
response.Usage = usage
nonStopFinishReason := ""
hasPayload := len(response.Choices) == 0 && usage != nil
for index := range geminiResponse.Candidates {
if index >= len(response.Choices) {
break
}
candidate := &geminiResponse.Candidates[index]
choice := &response.Choices[index]
if choice.FinishReason != nil && *choice.FinishReason != "" {
if nonStopFinishReason == "" {
nonStopFinishReason = *choice.FinishReason
}
choice.FinishReason = nil
}
if len(choice.Delta.ToolCalls) > 0 {
s.sawToolCall = true
}
for toolIndex := range choice.Delta.ToolCalls {
callID := strings.TrimSpace(choice.Delta.ToolCalls[toolIndex].ID)
indexesByID := s.toolIndexByCandidateID[candidate.Index]
@@ -431,31 +432,24 @@ func (s *GeminiToChatStreamState) ConvertChunk(geminiResponse *dto.GeminiChatRes
candidate.Index,
s.sentGroundingAnnotations,
)
}
if response.IsToolCall() {
s.sawToolCall = true
if !hasNonStopFinish {
for i := range response.Choices {
if response.Choices[i].FinishReason != nil && *response.Choices[i].FinishReason == types.FinishReasonToolCalls {
response.Choices[i].FinishReason = nil
}
}
if choice.Delta.GetContentString() != "" ||
choice.Delta.GetReasoningContent() != "" ||
len(choice.Delta.ToolCalls) > 0 ||
len(choice.Delta.Annotations) > 0 {
hasPayload = true
}
}
if usage != nil {
s.latestUsage = usage
}
for _, choice := range response.Choices {
if choice.FinishReason != nil && *choice.FinishReason != "" {
s.finishEmitted = true
break
}
}
responses := []*dto.ChatCompletionsStreamResponse{response}
if isStop && !s.finishEmitted {
responses = append(responses, s.terminalChunk(model))
responses := make([]*dto.ChatCompletionsStreamResponse, 0, 2)
if hasPayload && (!s.finishEmitted || len(response.Choices) == 0) {
responses = append(responses, response)
}
if (isStop || nonStopFinishReason != "") && !s.finishEmitted {
responses = append(responses, s.terminalChunk(model, nonStopFinishReason))
}
return responses, nil
}
@@ -479,7 +473,7 @@ func (s *GeminiToChatStreamState) Finalize(model string) ([]*dto.ChatCompletions
if s.finishEmitted {
return nil, nil
}
return []*dto.ChatCompletionsStreamResponse{s.terminalChunk(model)}, nil
return []*dto.ChatCompletionsStreamResponse{s.terminalChunk(model, "")}, nil
}
func (s *GeminiToChatStreamState) Usage() *dto.Usage {
@@ -717,10 +711,12 @@ func setGeminiPartialArgValue(current any, path []geminiPartialArgPathSegment, v
return object, nil
}
func (s *GeminiToChatStreamState) terminalChunk(model string) *dto.ChatCompletionsStreamResponse {
finishReason := types.FinishReasonStop
if s.sawToolCall {
finishReason = types.FinishReasonToolCalls
func (s *GeminiToChatStreamState) terminalChunk(model string, finishReason string) *dto.ChatCompletionsStreamResponse {
if finishReason == "" {
finishReason = types.FinishReasonStop
if s.sawToolCall {
finishReason = types.FinishReasonToolCalls
}
}
s.finishEmitted = true
return &dto.ChatCompletionsStreamResponse{
+18 -13
View File
@@ -5,6 +5,7 @@ import (
"github.com/QuantumNous/new-api/controller"
"github.com/QuantumNous/new-api/middleware"
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/service/authz"
// Import oauth package to register providers via init()
@@ -145,15 +146,15 @@ func SetApiRouter(router *gin.Engine) {
alipay.POST("/orders/:trade_no/refresh", middleware.UserCriticalRateLimit("alipay-direct-refresh"), controller.RefreshAlipayDirectUserOrder)
selfRoute.GET("/topup/self", controller.GetUserTopUps)
selfRoute.POST("/topup", middleware.CriticalRateLimit(), controller.TopUp)
selfRoute.POST("/pay", middleware.CriticalRateLimit(), controller.RequestEpay)
selfRoute.POST("/amount", controller.RequestAmount)
selfRoute.POST("/stripe/pay", middleware.CriticalRateLimit(), controller.RequestStripePay)
selfRoute.POST("/stripe/amount", controller.RequestStripeAmount)
selfRoute.POST("/creem/pay", middleware.CriticalRateLimit(), controller.RequestCreemPay)
selfRoute.POST("/waffo/amount", controller.RequestWaffoAmount)
selfRoute.POST("/waffo/pay", middleware.CriticalRateLimit(), controller.RequestWaffoPay)
selfRoute.POST("/waffo-pancake/amount", controller.RequestWaffoPancakeAmount)
selfRoute.POST("/waffo-pancake/pay", middleware.CriticalRateLimit(), controller.RequestWaffoPancakePay)
selfRoute.POST("/pay", middleware.CriticalRateLimit(), controller.RequirePaymentGateway(model.PaymentProviderEpay, false), controller.RequestEpay)
selfRoute.POST("/amount", controller.RequirePaymentGateway(model.PaymentProviderEpay, false), controller.RequestAmount)
selfRoute.POST("/stripe/pay", middleware.CriticalRateLimit(), controller.RequirePaymentGateway(model.PaymentProviderStripe, false), controller.RequestStripePay)
selfRoute.POST("/stripe/amount", controller.RequirePaymentGateway(model.PaymentProviderStripe, false), controller.RequestStripeAmount)
selfRoute.POST("/creem/pay", middleware.CriticalRateLimit(), controller.RequirePaymentGateway(model.PaymentProviderCreem, false), controller.RequestCreemPay)
selfRoute.POST("/waffo/amount", controller.RequirePaymentGateway(model.PaymentProviderWaffo, false), controller.RequestWaffoAmount)
selfRoute.POST("/waffo/pay", middleware.CriticalRateLimit(), controller.RequirePaymentGateway(model.PaymentProviderWaffo, false), controller.RequestWaffoPay)
selfRoute.POST("/waffo-pancake/amount", controller.RequirePaymentGateway(model.PaymentProviderWaffoPancake, false), controller.RequestWaffoPancakeAmount)
selfRoute.POST("/waffo-pancake/pay", middleware.CriticalRateLimit(), controller.RequirePaymentGateway(model.PaymentProviderWaffoPancake, false), controller.RequestWaffoPancakePay)
selfRoute.POST("/aff_transfer", middleware.UserCriticalRateLimit("aff-transfer"), controller.TransferAffQuota)
selfRoute.PUT("/setting", controller.UpdateUserSetting)
@@ -226,10 +227,10 @@ func SetApiRouter(router *gin.Engine) {
subscriptionRoute.GET("/self", controller.GetSubscriptionSelf)
subscriptionRoute.PUT("/self/preference", controller.UpdateSubscriptionPreference)
subscriptionRoute.POST("/balance/pay", middleware.CriticalRateLimit(), controller.SubscriptionRequestBalancePay)
subscriptionRoute.POST("/epay/pay", middleware.CriticalRateLimit(), controller.SubscriptionRequestEpay)
subscriptionRoute.POST("/stripe/pay", middleware.CriticalRateLimit(), controller.SubscriptionRequestStripePay)
subscriptionRoute.POST("/creem/pay", middleware.CriticalRateLimit(), controller.SubscriptionRequestCreemPay)
subscriptionRoute.POST("/waffo-pancake/pay", middleware.CriticalRateLimit(), controller.SubscriptionRequestWaffoPancakePay)
subscriptionRoute.POST("/epay/pay", middleware.CriticalRateLimit(), controller.RequirePaymentGateway(model.PaymentProviderEpay, true), controller.SubscriptionRequestEpay)
subscriptionRoute.POST("/stripe/pay", middleware.CriticalRateLimit(), controller.RequirePaymentGateway(model.PaymentProviderStripe, true), controller.SubscriptionRequestStripePay)
subscriptionRoute.POST("/creem/pay", middleware.CriticalRateLimit(), controller.RequirePaymentGateway(model.PaymentProviderCreem, true), controller.SubscriptionRequestCreemPay)
subscriptionRoute.POST("/waffo-pancake/pay", middleware.CriticalRateLimit(), controller.RequirePaymentGateway(model.PaymentProviderWaffoPancake, true), controller.SubscriptionRequestWaffoPancakePay)
}
subscriptionAdminRoute := apiRouter.Group("/subscription/admin")
subscriptionAdminRoute.Use(middleware.AdminAuth())
@@ -275,6 +276,10 @@ func SetApiRouter(router *gin.Engine) {
optionRoute.POST("/model_pricing/convert", controller.PreviewModelPricingConversion)
optionRoute.POST("/model_pricing/preview", controller.PreviewModelPricing)
optionRoute.POST("/payment_compliance", controller.ConfirmPaymentCompliance)
paymentGateways := optionRoute.Group("/payment-gateways", middleware.DisableCache(), controller.AlipayDirectAdminSession)
paymentGateways.GET("", controller.GetPaymentGateways)
paymentGateways.PUT("/:gateway", controller.UpdatePaymentGateway)
paymentGateways.DELETE("/:gateway", controller.ClearPaymentGateway)
alipay := optionRoute.Group("/alipay-direct", middleware.DisableCache(), controller.AlipayDirectAdminSession)
alipay.GET("", controller.GetAlipayDirectAdmin)
alipay.PUT("", controller.UpdateAlipayDirectAdmin)
+11 -1
View File
@@ -249,8 +249,18 @@ func verifySupportTicketRoutes(t *testing.T, dsn string, upgrade bool) {
longDescription := strings.Repeat("🧪", 125)
longReport := readSupportTicketResponse[model.SupportTicket](t, request(http.MethodPost, userPath, ownerSession.AccessToken,
`{"category":"account","body":"`+longDescription+`"}`))
`{"category":"report","body":"`+longDescription+`"}`))
assert.Equal(t, model.SupportTicketCategory("report"), longReport.Category)
assert.Equal(t, strings.Repeat("🧪", 119)+"…", longReport.Subject)
for _, view := range []struct{ path, token string }{
{userPath, ownerSession.AccessToken}, {adminPath, staffSession.AccessToken},
} {
reports := readSupportTicketResponse[struct {
Items []model.SupportTicket `json:"items"`
}](t, request(http.MethodGet, view.path+"?category=report", view.token, ""))
require.Len(t, reports.Items, 1)
assert.Equal(t, longReport.Id, reports.Items[0].Id)
}
longDetail := readSupportTicketResponse[model.SupportTicketDetail](t, request(http.MethodGet,
fmt.Sprintf("%s/%d", userPath, longReport.Id), ownerSession.AccessToken, ""))
require.Len(t, longDetail.Messages, 1)
+3 -3
View File
@@ -107,9 +107,9 @@ func (s *BillingSession) Settle(actualQuota int) error {
s.relayInfo.UserId, s.relayInfo.TokenId, delta, tokenErr.Error()))
}
}
// 3) 更新 relayInfo 上的订阅 PostDelta(用于日志)
if s.funding.Source() == BillingSourceSubscription {
s.relayInfo.SubscriptionPostDelta += int64(delta)
// 3) 更新 relayInfo 上的订阅 PostDelta(用于日志),按实际生效的差额计
if sub, ok := s.funding.(*SubscriptionFunding); ok {
s.relayInfo.SubscriptionPostDelta += sub.settledDelta
}
s.settled, s.actualQuota, s.settlementErr = true, actualQuota, tokenErr
return tokenErr
+1 -1
View File
@@ -41,7 +41,7 @@ func AppendTaskPluginIdentityFilter(c *gin.Context, pluginKey string) {
}
if c.Request != nil && c.Request.URL != nil {
// An ordinary request may run on a plugin channel whose relay routes serve its path.
filter.RequestPath = c.Request.URL.Path
filter.RequestPath = common.NormalizeRelayPath(c.Request.URL.Path)
}
GetChannelConstraints(c).AddFilter(filter)
}
+8 -1
View File
@@ -140,6 +140,7 @@ type SubscriptionFunding struct {
amount int64 // 预扣的订阅额度(subConsume)
subscriptionId int
preConsumed int64
settledDelta int64
// 以下字段在 PreConsume 成功后填充,供 RelayInfo 同步使用
AmountTotal int64
AmountUsedAfter int64
@@ -169,9 +170,15 @@ func (s *SubscriptionFunding) PreConsume(_ int) error {
func (s *SubscriptionFunding) Settle(delta int) error {
if delta == 0 {
s.settledDelta = 0
return nil
}
return model.PostConsumeUserSubscriptionDelta(s.subscriptionId, int64(delta))
applied, err := model.SettleUserSubscriptionDelta(s.subscriptionId, int64(delta))
if err != nil {
return err
}
s.settledDelta = applied
return nil
}
func (s *SubscriptionFunding) Refund() error {
+272
View File
@@ -0,0 +1,272 @@
package service
import (
"context"
"fmt"
"math"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/model"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/relaykit/dto"
"github.com/QuantumNous/new-api/relaykit/types"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func setupSubscriptionSettleTables(t *testing.T) {
t.Helper()
truncate(t)
require.NoError(t, model.DB.AutoMigrate(&model.SubscriptionPlan{}, &model.SubscriptionPreConsumeRecord{}))
t.Cleanup(func() {
model.DB.Exec("DELETE FROM subscription_pre_consume_records")
model.DB.Exec("DELETE FROM subscription_plans")
_ = model.PurgeSubscriptionPlanCache()
})
}
func seedSubscriptionPlanAndInstance(t *testing.T, userID int, total int64, used int64, allowWalletOverflow bool, endOffset time.Duration) *model.UserSubscription {
t.Helper()
plan := &model.SubscriptionPlan{
Title: fmt.Sprintf("Plan-%d", total),
DurationUnit: model.SubscriptionDurationDay,
DurationValue: 1,
TotalAmount: total,
QuotaResetPeriod: model.SubscriptionResetNever,
AllowWalletOverflow: common.GetPointer(allowWalletOverflow),
Enabled: true,
}
require.NoError(t, model.DB.Create(plan).Error)
now := model.GetDBTimestamp()
sub := &model.UserSubscription{
UserId: userID,
PlanId: plan.Id,
AmountTotal: total,
AmountUsed: used,
StartTime: now,
EndTime: now + int64(endOffset.Seconds()),
Status: "active",
AllowWalletOverflow: allowWalletOverflow,
}
require.NoError(t, model.DB.Create(sub).Error)
return sub
}
func newBillingTestContext(t *testing.T) *gin.Context {
t.Helper()
gin.SetMode(gin.TestMode)
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
return c
}
func TestSettleUserSubscriptionDelta(t *testing.T) {
setupSubscriptionSettleTables(t)
const userID = 901
seedUser(t, userID, 0)
t.Run("finite plan caps overrun and floors refund", func(t *testing.T) {
sub := seedSubscriptionPlanAndInstance(t, userID, 100, 0, false, time.Hour)
steps := []struct {
name string
delta int64
wantApplied int64
wantUsed int64
}{
{name: "normal charge", delta: 40, wantApplied: 40, wantUsed: 40},
{name: "overrun capped at total", delta: 75, wantApplied: 60, wantUsed: 100},
{name: "full plan avoids int64 overflow", delta: math.MaxInt64, wantApplied: 0, wantUsed: 100},
{name: "refund clamped at zero", delta: -500, wantApplied: -100, wantUsed: 0},
{name: "zero delta is no-op", delta: 0, wantApplied: 0, wantUsed: 0},
}
for _, tc := range steps {
applied, err := model.SettleUserSubscriptionDelta(sub.Id, tc.delta)
require.NoError(t, err, tc.name)
assert.Equal(t, tc.wantApplied, applied, tc.name)
assert.Equal(t, tc.wantUsed, getSubscriptionUsed(t, sub.Id), tc.name)
}
})
t.Run("unlimited plan saturates at MaxInt64 without overflow", func(t *testing.T) {
sub := seedSubscriptionPlanAndInstance(t, userID, 0, math.MaxInt64-10, false, time.Hour)
applied, err := model.SettleUserSubscriptionDelta(sub.Id, 100)
require.NoError(t, err)
assert.Equal(t, int64(10), applied)
assert.Equal(t, int64(math.MaxInt64), getSubscriptionUsed(t, sub.Id))
applied, err = model.SettleUserSubscriptionDelta(sub.Id, 1)
require.NoError(t, err)
assert.Zero(t, applied)
assert.Equal(t, int64(math.MaxInt64), getSubscriptionUsed(t, sub.Id))
})
t.Run("invalid subscription id returns error", func(t *testing.T) {
for _, id := range []int{0, -1} {
applied, err := model.SettleUserSubscriptionDelta(id, 10)
require.Error(t, err)
assert.Zero(t, applied)
}
})
}
func TestBillingSessionSubscriptionSettleOverrunSwitchesPlanAndRejects(t *testing.T) {
setupSubscriptionSettleTables(t)
const (
userID = 902
tokenID = 902
tokenInitialQuota = 40_000_000
planTotal = int64(15_000_000)
preConsume = 5_000
actualQuota = 2_250_375
fullDelta = int64(actualQuota - preConsume)
requestsPerPlan = 7
lastAppliedDelta = planTotal - int64(requestsPerPlan-1)*int64(actualQuota) - int64(preConsume)
)
seedUser(t, userID, 0)
seedToken(t, tokenID, userID, "sk-sub-overrun-switch", tokenInitialQuota)
subA := seedSubscriptionPlanAndInstance(t, userID, planTotal, 0, false, time.Hour)
subB := seedSubscriptionPlanAndInstance(t, userID, planTotal, 0, false, 2*time.Hour)
runRequest := func(seq int) (*relaycommon.RelayInfo, *types.NewAPIError) {
c := newBillingTestContext(t)
info := &relaycommon.RelayInfo{
RequestId: fmt.Sprintf("req-sub-overrun-%d", seq),
UserId: userID,
TokenId: tokenID,
TokenKey: "sk-sub-overrun-switch",
OriginModelName: "test-model",
UserSetting: dto.UserSetting{
BillingPreference: "subscription_first",
QuotaWarningEnabled: common.GetPointer(false),
},
}
if apiErr := PreConsumeBilling(c, preConsume, info); apiErr != nil {
return info, apiErr
}
require.NoError(t, SettleBilling(c, info, actualQuota))
return info, nil
}
// Requests 1..7 exhaust subscription A; request 7 caps at planTotal.
for i := range requestsPerPlan {
info, apiErr := runRequest(i + 1)
require.Nil(t, apiErr, "request %d should succeed on sub A", i+1)
assert.Equal(t, subA.Id, info.SubscriptionId)
if i < requestsPerPlan-1 {
assert.Equal(t, fullDelta, info.SubscriptionPostDelta)
} else {
assert.Equal(t, lastAppliedDelta, info.SubscriptionPostDelta)
require.NoError(t, info.Billing.Settle(actualQuota), "repeated settle must be idempotent")
assert.Equal(t, lastAppliedDelta, info.SubscriptionPostDelta)
other := model.NewLogOther()
appendBillingInfo(info, other)
snap := other.Snapshot()
assert.Equal(t, int64(preConsume)+lastAppliedDelta, snap["subscription_consumed"])
assert.Equal(t, int64(0), snap["subscription_remain"])
assert.Equal(t, planTotal, snap["subscription_used"])
}
}
assert.Equal(t, planTotal, getSubscriptionUsed(t, subA.Id))
assert.Zero(t, getSubscriptionUsed(t, subB.Id))
// Requests 8..14 automatically switch to subscription B and exhaust it.
for i := range requestsPerPlan {
info, apiErr := runRequest(requestsPerPlan + i + 1)
require.Nil(t, apiErr, "request %d should succeed on sub B", requestsPerPlan+i+1)
assert.Equal(t, subB.Id, info.SubscriptionId)
if i == requestsPerPlan-1 {
assert.Equal(t, lastAppliedDelta, info.SubscriptionPostDelta)
}
}
assert.Equal(t, planTotal, getSubscriptionUsed(t, subB.Id))
// Request 15 is rejected at pre-consume because both plans are full and wallet overflow is disabled.
_, apiErr := runRequest(2*requestsPerPlan + 1)
require.NotNil(t, apiErr)
assert.Equal(t, http.StatusForbidden, apiErr.StatusCode)
assert.Equal(t, types.ErrorCodeInsufficientUserQuota, apiErr.GetErrorCode())
// Token quota still accounts for the full actual cost of all 14 completed requests.
assert.Equal(t, tokenInitialQuota-2*requestsPerPlan*actualQuota, getTokenRemainQuota(t, tokenID))
}
func TestPostConsumeQuotaRejectsSubscriptionOverrun(t *testing.T) {
setupSubscriptionSettleTables(t)
const (
userID = 903
tokenID = 903
tokenRemain = 10_000
)
seedUser(t, userID, 0)
seedToken(t, tokenID, userID, "sk-sub-strict-post", tokenRemain)
sub := seedSubscriptionPlanAndInstance(t, userID, 100, 90, false, time.Hour)
info := &relaycommon.RelayInfo{
UserId: userID,
TokenId: tokenID,
TokenKey: "sk-sub-strict-post",
BillingSource: BillingSourceSubscription,
SubscriptionId: sub.Id,
}
// PostConsumeQuota backs Realtime PreWssConsumeQuota and must stay strict.
err := PostConsumeQuota(info, 25, 0, false)
require.Error(t, err)
assert.Contains(t, err.Error(), "subscription used exceeds total")
assert.Equal(t, int64(90), getSubscriptionUsed(t, sub.Id))
assert.Zero(t, info.SubscriptionPostDelta)
assert.Equal(t, tokenRemain, getTokenRemainQuota(t, tokenID))
}
func TestRecalculateTaskQuota_SubscriptionOverrunCapsPlan(t *testing.T) {
setupSubscriptionSettleTables(t)
ctx := context.Background()
const (
userID = 904
tokenID = 904
channelID = 904
preConsumed = 50
actualQuota = 200
tokenRemain = 500
)
seedUser(t, userID, 0)
seedToken(t, tokenID, userID, "sk-sub-task-overrun", tokenRemain)
seedChannel(t, channelID)
sub := seedSubscriptionPlanAndInstance(t, userID, 1000, 950, false, time.Hour)
seedChargedAccounting(t, userID, channelID, tokenID, preConsumed, 1)
task := makeTask(userID, channelID, preConsumed, tokenID, BillingSourceSubscription, sub.Id)
require.NoError(t, model.DB.Create(task).Error)
RecalculateTaskQuota(ctx, task, actualQuota, common.NewMessage("subscription overrun settle"))
assert.Equal(t, int64(1000), getSubscriptionUsed(t, sub.Id))
assert.Equal(t, actualQuota, task.Quota)
assert.Equal(t, actualQuota, getTaskQuota(t, task.ID))
assert.Equal(t, tokenRemain-(actualQuota-preConsumed), getTokenRemainQuota(t, tokenID))
usedQuota, requestCount := getUserUsageAccounting(t, userID)
assert.Equal(t, actualQuota, usedQuota)
assert.Equal(t, 1, requestCount)
assert.Equal(t, int64(actualQuota), getChannelUsedQuota(t, channelID))
log := getLastLog(t)
require.NotNil(t, log)
assert.Equal(t, model.LogTypeConsume, log.Type)
assert.Equal(t, actualQuota-preConsumed, log.Quota)
}
+2 -1
View File
@@ -126,7 +126,8 @@ func taskAdjustFunding(task *model.Task, delta int) error {
return fmt.Errorf("durable wallet task requires a terminal settlement intent")
}
if taskIsSubscription(task) {
return model.PostConsumeUserSubscriptionDelta(task.PrivateData.SubscriptionId, int64(delta))
_, err := model.SettleUserSubscriptionDelta(task.PrivateData.SubscriptionId, int64(delta))
return err
}
if delta > 0 {
return model.DecreaseUserQuota(task.UserId, delta, false)
+5 -22
View File
@@ -6,7 +6,6 @@ import (
"strings"
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/setting"
pancake "github.com/waffo-com/waffo-pancake-sdk-go"
)
@@ -72,17 +71,6 @@ func (e *WaffoPancakeWebhookEvent) NormalizedEventType() string {
return e.EventType
}
// newWaffoPancakeClient builds an SDK client from persisted settings. The
// runtime checkout / webhook paths use this; configuration endpoints use
// newWaffoPancakeClientFromCreds so the operator can verify typed-but-not-
// yet-saved credentials.
func newWaffoPancakeClient() (*pancake.Client, error) {
return pancake.New(pancake.Config{
MerchantID: setting.WaffoPancakeMerchantID,
PrivateKey: setting.WaffoPancakePrivateKey,
})
}
func newWaffoPancakeClientFromCreds(merchantID, privateKey string) (*pancake.Client, error) {
if strings.TrimSpace(merchantID) == "" || strings.TrimSpace(privateKey) == "" {
return nil, fmt.Errorf("merchant id and private key are required")
@@ -96,7 +84,7 @@ func newWaffoPancakeClientFromCreds(merchantID, privateKey string) (*pancake.Cli
// CreateWaffoPancakeCheckoutSession creates an Authenticated-mode checkout
// session: the order is bound to BuyerIdentity (stable per user) so it stays
// attributable even if the buyer edits the email on Waffo's checkout form.
func CreateWaffoPancakeCheckoutSession(ctx context.Context, params *WaffoPancakeCreateSessionParams) (*WaffoPancakeCheckoutSession, error) {
func CreateWaffoPancakeCheckoutSession(ctx context.Context, params *WaffoPancakeCreateSessionParams, merchantID, privateKey string) (*WaffoPancakeCheckoutSession, error) {
if params == nil {
return nil, fmt.Errorf("missing checkout params")
}
@@ -106,10 +94,7 @@ func CreateWaffoPancakeCheckoutSession(ctx context.Context, params *WaffoPancake
if strings.TrimSpace(params.OrderMerchantExternalID) == "" {
return nil, fmt.Errorf("missing order merchant external id")
}
if strings.TrimSpace(setting.WaffoPancakeStoreID) == "" {
return nil, fmt.Errorf("missing Waffo Pancake store id")
}
client, err := newWaffoPancakeClient()
client, err := newWaffoPancakeClientFromCreds(merchantID, privateKey)
if err != nil {
return nil, fmt.Errorf("build Waffo Pancake client: %w", err)
}
@@ -162,16 +147,14 @@ func WaffoPancakeBuyerIdentityFromUserID(userID int) string {
return fmt.Sprintf("new-api-user-%d", userID)
}
// VerifyConfiguredWaffoPancakeWebhook verifies the signature header. The SDK
// VerifyWaffoPancakeWebhook verifies the signature header. The SDK
// picks the matching test / prod public key from the payload's `mode` field.
func VerifyConfiguredWaffoPancakeWebhook(payload string, signatureHeader string) (*WaffoPancakeWebhookEvent, error) {
func VerifyWaffoPancakeWebhook(payload string, signatureHeader string) (*WaffoPancakeWebhookEvent, error) {
evt, err := pancake.VerifyWebhookTyped[pancake.WebhookEventData](payload, signatureHeader, nil)
if err != nil {
return nil, err
}
if storeID := strings.TrimSpace(setting.WaffoPancakeStoreID); storeID == "" || evt.StoreID != storeID {
return nil, fmt.Errorf("Waffo Pancake webhook store mismatch")
}
identity := ""
if evt.Data.MerchantProvidedBuyerIdentity != nil {
identity = *evt.Data.MerchantProvidedBuyerIdentity
+2
View File
@@ -62,6 +62,7 @@ type LegacyComboboxProps = {
'aria-labelledby'?: string
'aria-describedby'?: string
'aria-invalid'?: React.AriaAttributes['aria-invalid']
'aria-required'?: boolean
}
function Combobox(props: LegacyComboboxProps): React.ReactElement
@@ -147,6 +148,7 @@ function OptionCombobox(props: LegacyComboboxProps) {
aria-labelledby={props['aria-labelledby']}
aria-describedby={props['aria-describedby']}
aria-invalid={props['aria-invalid']}
aria-required={props['aria-required']}
placeholder={
props.searchPlaceholder ?? props.placeholder ?? t('Search...')
}
@@ -1103,6 +1103,55 @@ test('a failed creation keeps its draft and prevents duplicate submission while
expect(screen.getByLabelText('Name *')).toHaveValue('Video A')
})
test.each(['create', 'edit'] as const)(
'VolcEngine %s exposes upstream discovery and lets users select fetched models',
async (mode) => {
editingChannel.type = 45
const post = vi.spyOn(api, 'post').mockResolvedValue({
data: { success: true, data: ['upstream-model'] },
})
const user = userEvent.setup()
render(
<ConfigurationHarness
currentRow={mode === 'edit' ? editingChannel : undefined}
/>
)
if (mode === 'create') {
await user.click(screen.getByRole('option', { name: /^VolcEngine / }))
fireEvent.change(screen.getByLabelText('API Key *'), {
target: { value: 'test-key' },
})
} else {
await screen.findByDisplayValue('Existing channel')
}
const fetch = screen.getByRole('button', { name: 'Fetch from Upstream' })
expect(fetch).toBeEnabled()
await user.click(fetch)
await user.click(
await screen.findByRole('checkbox', { name: 'upstream-model' })
)
expect(screen.getByRole('button', { name: 'upstream-model' })).toBeVisible()
if (mode === 'create') {
expect(post).toHaveBeenCalledWith(
'/api/channel/fetch_models',
expect.objectContaining({
type: 45,
key: 'test-key',
base_url: 'https://ark.cn-beijing.volces.com',
}),
expect.anything()
)
} else {
expect(api.get).toHaveBeenCalledWith(
'/api/channel/fetch_models/42',
expect.anything()
)
expect(post).not.toHaveBeenCalled()
}
}
)
test('model discovery discards a response for old credentials and retains manually selected models', async () => {
const oldReply = deferredResponse<{
data: { success: boolean; data: string[] }
+1
View File
@@ -519,6 +519,7 @@ export const MODEL_FETCHABLE_TYPES = new Set([
40,
42,
43,
45,
47,
48,
57,
@@ -0,0 +1,60 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { describe, expect, it } from 'vitest'
import { resolveChatUrl } from '../chat-links'
function decodeProvider(template: string, serverAddress: string): unknown {
const link = new URL(
resolveChatUrl({ template, serverAddress, apiKey: 'sk-test-only' })
)
return JSON.parse(atob(link.searchParams.get('data') ?? ''))
}
describe('desktop chat provider import', () => {
it('prefills AionUI v2 with the platform, address and API key', () => {
const payload = decodeProvider(
'aionui://provider/add?v=1&data={aionuiConfig}',
'https://api.example.test'
)
expect(payload).toEqual({
platform: 'new-api',
base_url: 'https://api.example.test',
api_key: 'sk-test-only',
})
})
it.each([
'https://api.example.test/gateway/',
'https://api.example.test/gateway/v1/',
])(
'imports a DeepChat base URL with a single version suffix from %s',
(serverAddress) => {
const payload = decodeProvider(
'deepchat://provider/install?v=1&data={deepchatConfig}',
serverAddress
)
expect(payload).toEqual({
id: 'new-api',
baseUrl: 'https://api.example.test/gateway/v1',
apiKey: 'sk-test-only',
})
}
)
})
+7 -3
View File
@@ -174,17 +174,21 @@ export function resolveChatUrl({
if (url.includes('{aionuiConfig}')) {
const payload = {
platform: 'new-api',
baseUrl: safeServerAddress,
apiKey: safeApiKey,
base_url: safeServerAddress,
api_key: safeApiKey,
}
const encoded = encodeURIComponent(toBase64(JSON.stringify(payload)))
return replaceToken(url, '{aionuiConfig}', encoded)
}
if (url.includes('{deepchatConfig}')) {
const baseUrl = safeServerAddress
.trim()
.replace(/\/+$/, '')
.replace(/\/v1$/, '')
const payload = {
id: 'new-api',
baseUrl: safeServerAddress,
baseUrl: baseUrl ? `${baseUrl}/v1` : '',
apiKey: safeApiKey,
}
const encoded = encodeURIComponent(toBase64(JSON.stringify(payload)))
@@ -16,13 +16,17 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useChatPresets } from '@/features/chat/hooks/use-chat-presets'
import { ApiKeysDeleteDialog } from './api-keys-delete-dialog'
import { ApiKeysMutateDrawer } from './api-keys-mutate-drawer'
import { useApiKeys } from './api-keys-provider'
import { CCSwitchDialog } from './dialogs/cc-switch-dialog'
export function ApiKeysDialogs() {
const { open, setOpen, currentRow, resolvedKey } = useApiKeys()
const { open, setOpen, currentRow, resolvedKey, setResolvedKey } =
useApiKeys()
const { serverAddress } = useChatPresets()
return (
<>
@@ -34,8 +38,13 @@ export function ApiKeysDialogs() {
<ApiKeysDeleteDialog />
<CCSwitchDialog
open={open === 'cc-switch'}
onOpenChange={(isOpen) => !isOpen && setOpen(null)}
onOpenChange={(isOpen) => {
if (isOpen) return
setOpen(null)
setResolvedKey('')
}}
tokenKey={resolvedKey}
serverAddress={serverAddress}
/>
</>
)
@@ -33,22 +33,144 @@ beforeEach(() => {
afterEach(() => {
queryClient.clear()
vi.restoreAllMocks()
})
function renderDialog(models = ['gpt-5.4', 'claude-sonnet-4-6']) {
function renderDialog(
models = ['gpt-5.4', 'claude-sonnet-4-6'],
serverAddress = 'https://gateway.example.test/proxy/v1/',
tokenKey = 'test-only'
) {
queryClient.setQueryData(['user-models-ccswitch'], {
success: true,
data: models,
})
render(
<QueryClientProvider client={queryClient}>
<CCSwitchDialog open onOpenChange={vi.fn()} tokenKey='test-only' />
<CCSwitchDialog
open
onOpenChange={vi.fn()}
tokenKey={tokenKey}
serverAddress={serverAddress}
/>
</QueryClientProvider>
)
}
describe('CC Switch provider import', () => {
it.each([
['Claude Code', 'claude', 'anthropic', '', false],
['Claude Desktop', 'claude-desktop', 'anthropic', '', false],
['Codex', 'codex', 'openai_responses', '/v1', false],
['Gemini CLI', 'gemini', 'gemini_native', '', false],
['Antigravity CLI', 'agy', 'gemini_native', '', false],
['Grok Build', 'grokbuild', 'openai_responses', '/v1', false],
['OpenCode', 'opencode', 'openai_chat', '/v1', true],
['OpenClaw', 'openclaw', 'openai_chat', '/v1', true],
['Hermes', 'hermes', 'openai_chat', '/v1', true],
['Pi', 'pi', 'openai_chat', '/v1', true],
['MiniMax Code', 'mcode', 'openai_chat', '/v1', true],
['Kimi Code', 'kimi', 'openai_chat', '/v1', true],
['DeepSeek Harness', 'dsh', 'openai_chat', '/v1', true],
['Oh My Pi', 'omp', 'openai_chat', '/v1', true],
['GitHub Copilot CLI', 'copilot', 'openai_chat', '/v1', true],
['WorkBuddy', 'workbuddy', 'openai_chat', '/v1/chat/completions', true],
['ZCode', 'zcode', 'openai_chat', '/v1', true],
])(
'opens a v1 import with the native configuration for %s',
async (label, app, format, suffix, requiresModel) => {
const open = vi.spyOn(window, 'open').mockReturnValue(null)
renderDialog()
const user = userEvent.setup()
await user.click(screen.getByRole('radio', { name: label }))
if (requiresModel) {
await user.click(
screen.getByRole('combobox', { name: 'Primary Model' })
)
await user.click(screen.getByRole('option', { name: 'gpt-5.4' }))
}
const name = screen.getByRole('textbox', { name: 'Name' })
await user.clear(name)
await user.type(name, '站点 + AI & Co')
await user.click(screen.getByRole('button', { name: 'Open CC Switch' }))
expect(open).toHaveBeenCalledOnce()
const [href, target, features] = open.mock.calls[0]
const url = new URL(String(href))
expect([url.protocol, url.host, url.pathname]).toEqual([
'ccswitch:',
'v1',
'/import',
])
expect(Object.fromEntries(url.searchParams)).toEqual({
resource: 'provider',
app,
apiFormat: format,
name: '站点 + AI & Co',
endpoint: `https://gateway.example.test/proxy${suffix}`,
apiKey: 'sk-test-only',
homepage: 'https://gateway.example.test/proxy',
...(requiresModel && {
model: 'gpt-5.4',
}),
})
expect([target, features]).toEqual(['_blank', 'noopener,noreferrer'])
expect(screen.getByRole('dialog')).toBeVisible()
}
)
it('lets Claude Code clear model overrides and import using its own defaults', async () => {
const open = vi.spyOn(window, 'open').mockReturnValue(null)
renderDialog(undefined, 'http://127.0.0.1:3001/', 'sk-test-only')
const user = userEvent.setup()
const input = screen.getByRole('combobox', { name: 'Sonnet Model' })
await user.click(input)
await user.click(screen.getByRole('option', { name: 'claude-sonnet-4-6' }))
await user.click(screen.getByRole('button', { name: 'Open CC Switch' }))
const first = new URL(String(open.mock.calls[0][0])).searchParams
expect(first.get('sonnetModel')).toBe('claude-sonnet-4-6')
expect(first.get('apiKey')).toBe('sk-test-only')
expect(first.get('endpoint')).toBe('http://127.0.0.1:3001')
await user.click(input)
await user.click(screen.getByRole('option', { name: 'Use default' }))
await user.click(screen.getByRole('button', { name: 'Open CC Switch' }))
expect(
new URL(String(open.mock.calls[1][0])).searchParams.has('sonnetModel')
).toBe(false)
})
it('requires a model to import into Pi', async () => {
const open = vi.spyOn(window, 'open').mockReturnValue(null)
renderDialog()
const user = userEvent.setup()
await user.click(screen.getByRole('radio', { name: 'Pi' }))
expect(
screen.getByRole('combobox', { name: 'Primary Model' })
).toHaveAttribute('aria-required', 'true')
expect(
screen.getByRole('button', { name: 'Open CC Switch' })
).toBeDisabled()
expect(open).not.toHaveBeenCalled()
})
it.each([
['https://example.test', ''],
['http://example.test', 'test-only'],
['https://user:password@example.test', 'test-only'],
['https://example.test/?token=test', 'test-only'],
['https://example.test/,https://other.example.test', 'test-only'],
])('blocks import with unsafe or missing input (%s)', (address, key) => {
renderDialog([], address, key)
expect(
screen.getByRole('button', { name: 'Open CC Switch' })
).toBeDisabled()
})
})
describe('CC Switch model selection', () => {
it.each(['Claude', 'Codex', 'Gemini'])(
it.each(['Claude Code', 'Codex', 'Gemini CLI'])(
'opens %s models outside the clipping dialog and keeps the dialog open after selection',
async (app) => {
renderDialog()
@@ -19,7 +19,6 @@ For commercial licensing, please contact support@quantumnous.com
import { useQuery } from '@tanstack/react-query'
import { useState, useEffect, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import { Dialog } from '@/components/dialog'
import { Button } from '@/components/ui/button'
@@ -30,77 +29,38 @@ import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
import { getUserModels } from '@/lib/api'
import { requireServerSuccess } from '@/lib/server-error-message'
const APP_CONFIGS = {
claude: {
label: 'Claude',
defaultName: 'My Claude',
modelFields: [
{ key: 'model', labelKey: 'Primary Model', required: true },
{ key: 'haikuModel', labelKey: 'Haiku Model', required: false },
{ key: 'sonnetModel', labelKey: 'Sonnet Model', required: false },
{ key: 'opusModel', labelKey: 'Opus Model', required: false },
],
},
codex: {
label: 'Codex',
defaultName: 'My Codex',
modelFields: [{ key: 'model', labelKey: 'Primary Model', required: true }],
},
gemini: {
label: 'Gemini',
defaultName: 'My Gemini',
modelFields: [{ key: 'model', labelKey: 'Primary Model', required: true }],
},
} as const
import {
buildCCSwitchLink,
CC_SWITCH_APPS,
getCCSwitchAddress,
type CCSwitchApp,
type CCSwitchModelField,
} from '../../lib/cc-switch'
type AppType = keyof typeof APP_CONFIGS
const appOptions = Object.entries(CC_SWITCH_APPS)
const DEFAULT_APP = 'claude'
function getServerAddress(): string {
try {
const raw = localStorage.getItem('status')
if (raw) {
const status = JSON.parse(raw)
if (status.server_address) return status.server_address
}
} catch {
/* empty */
}
return window.location.origin
}
function buildCCSwitchURL(
app: string,
name: string,
models: Record<string, string>,
apiKey: string
): string {
const serverAddress = getServerAddress()
const endpoint = app === 'codex' ? `${serverAddress}/v1` : serverAddress
const params = new URLSearchParams()
params.set('resource', 'provider')
params.set('app', app)
params.set('name', name)
params.set('endpoint', endpoint)
params.set('apiKey', apiKey)
for (const [k, v] of Object.entries(models)) {
if (v) params.set(k, v)
}
params.set('homepage', serverAddress)
params.set('enabled', 'true')
return `ccswitch://v1/import?${params.toString()}`
}
const modelFields = [
{ key: 'model', labelKey: 'Primary Model' },
{ key: 'haikuModel', labelKey: 'Haiku Model' },
{ key: 'sonnetModel', labelKey: 'Sonnet Model' },
{ key: 'opusModel', labelKey: 'Opus Model' },
] as const
interface Props {
open: boolean
onOpenChange: (open: boolean) => void
tokenKey: string
serverAddress: string
}
export function CCSwitchDialog(props: Props) {
const { t } = useTranslation()
const [app, setApp] = useState<AppType>('claude')
const [name, setName] = useState<string>(APP_CONFIGS.claude.defaultName)
const [models, setModels] = useState<Record<string, string>>({})
const [app, setApp] = useState<CCSwitchApp>(DEFAULT_APP)
const [name, setName] = useState<string | null>(null)
const [models, setModels] = useState<
Partial<Record<CCSwitchModelField, string>>
>({})
const { data: modelsData } = useQuery({
queryKey: ['user-models-ccswitch'],
@@ -119,32 +79,36 @@ export function CCSwitchDialog(props: Props) {
// eslint-disable-next-line react-hooks/set-state-in-effect
setModels({})
setApp('claude')
setName(APP_CONFIGS.claude.defaultName)
setApp(DEFAULT_APP)
setName(null)
}
}, [props.open])
const currentConfig = APP_CONFIGS[app]
const currentConfig = CC_SWITCH_APPS[app]
const modelRequired = 'modelRequired' in currentConfig
const address = getCCSwitchAddress(props.serverAddress)
const defaultName = address ? new URL(address).hostname : currentConfig.label
const providerName = name ?? defaultName
const tokenKey = props.tokenKey.trim()
const canImport = Boolean(
address &&
tokenKey &&
tokenKey !== 'sk-' &&
providerName.trim() &&
(!modelRequired || models.model?.trim())
)
const handleAppChange = (val: string) => {
const appVal = val as AppType
setApp(appVal)
setName(APP_CONFIGS[appVal].defaultName)
const handleAppChange = (value: string): void => {
if (!Object.hasOwn(CC_SWITCH_APPS, value)) return
setApp(value as CCSwitchApp)
setModels({})
}
const handleSubmit = () => {
if (!models.model) {
toast.warning(t('Please select a primary model'))
return
}
const key = props.tokenKey.startsWith('sk-')
? props.tokenKey
: `sk-${props.tokenKey}`
const url = buildCCSwitchURL(app, name, models, key)
window.open(url, '_blank')
props.onOpenChange(false)
const handleSubmit = (): void => {
if (!canImport || !address) return
const link = buildCCSwitchLink(app, providerName, address, tokenKey, models)
// The browser must launch the native app within the user's click gesture.
window.open(link, '_blank', 'noopener,noreferrer')
}
return (
@@ -160,24 +124,22 @@ export function CCSwitchDialog(props: Props) {
<Button variant='outline' onClick={() => props.onOpenChange(false)}>
{t('Cancel')}
</Button>
<Button onClick={handleSubmit}>{t('Open CC Switch')}</Button>
<Button onClick={handleSubmit} disabled={!canImport}>
{t('Open CC Switch')}
</Button>
</>
}
>
<div className='space-y-4'>
<div className='space-y-2'>
<Label>{t('Application')}</Label>
<Label id='cc-switch-application'>{t('Application')}</Label>
<RadioGroup
aria-labelledby='cc-switch-application'
value={app}
onValueChange={handleAppChange}
className='flex gap-4'
className='grid grid-cols-2 gap-2 sm:grid-cols-3'
>
{(
Object.entries(APP_CONFIGS) as [
AppType,
(typeof APP_CONFIGS)[AppType],
][]
).map(([key, cfg]) => (
{appOptions.map(([key, cfg]) => (
<div key={key} className='flex items-center gap-2'>
<RadioGroupItem value={key} id={`app-${key}`} />
<Label htmlFor={`app-${key}`} className='cursor-pointer'>
@@ -192,30 +154,60 @@ export function CCSwitchDialog(props: Props) {
<Label htmlFor='cc-switch-name'>{t('Name')}</Label>
<Input
id='cc-switch-name'
value={name}
value={providerName}
onChange={(event) => setName(event.target.value)}
placeholder={currentConfig.defaultName}
placeholder={defaultName}
/>
</div>
{currentConfig.modelFields.map((field) => (
<div key={field.key} className='space-y-2'>
<Label htmlFor={`cc-switch-${field.key}`} required={field.required}>
{t(field.labelKey)}
</Label>
<Combobox
id={`cc-switch-${field.key}`}
aria-label={t(field.labelKey)}
options={modelOptions}
value={models[field.key] || ''}
onValueChange={(v) =>
setModels((prev) => ({ ...prev, [field.key]: v ?? '' }))
}
placeholder={t('Select or enter model name')}
emptyText={t('No models found')}
/>
</div>
))}
{(currentConfig.apiFormat === 'anthropic'
? modelFields
: modelFields.slice(0, 1)
).map((field) => {
const required = field.key === 'model' && modelRequired
const options =
!required && models[field.key]
? [{ value: '', label: t('Use default') }, ...modelOptions]
: modelOptions
return (
<div key={field.key} className='space-y-2'>
<Label htmlFor={`cc-switch-${field.key}`} required={required}>
{t(field.labelKey)}
</Label>
<Combobox
id={`cc-switch-${field.key}`}
aria-label={t(field.labelKey)}
aria-required={required}
options={options}
value={models[field.key] ?? ''}
onValueChange={(value) =>
setModels((prev) => ({ ...prev, [field.key]: value ?? '' }))
}
placeholder={t('Select model')}
emptyText={t('No models found')}
/>
</div>
)
})}
{!address && (
<p role='alert' className='text-destructive text-sm'>
{t(
'CC Switch import requires an HTTPS server address or a local loopback address.'
)}
</p>
)}
<p className='text-muted-foreground text-sm'>
{t('Use CC Switch v4.0.47 or later to confirm the import.')}{' '}
<a
href='https://github.com/farion1231/cc-switch/releases/latest'
target='_blank'
rel='noopener noreferrer'
className='underline underline-offset-4'
>
{t('Download')}
</a>
</p>
</div>
</Dialog>
)
+131
View File
@@ -0,0 +1,131 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
type ProviderConfig = {
label: string
apiFormat: 'anthropic' | 'openai_responses' | 'gemini_native' | 'openai_chat'
modelRequired?: boolean
}
// These are the native/default formats of the supported provider-import targets.
export const CC_SWITCH_APPS = {
claude: { label: 'Claude Code', apiFormat: 'anthropic' },
'claude-desktop': { label: 'Claude Desktop', apiFormat: 'anthropic' },
codex: { label: 'Codex', apiFormat: 'openai_responses' },
gemini: { label: 'Gemini CLI', apiFormat: 'gemini_native' },
agy: { label: 'Antigravity CLI', apiFormat: 'gemini_native' },
grokbuild: { label: 'Grok Build', apiFormat: 'openai_responses' },
opencode: {
label: 'OpenCode',
apiFormat: 'openai_chat',
modelRequired: true,
},
openclaw: {
label: 'OpenClaw',
apiFormat: 'openai_chat',
modelRequired: true,
},
hermes: { label: 'Hermes', apiFormat: 'openai_chat', modelRequired: true },
pi: { label: 'Pi', apiFormat: 'openai_chat', modelRequired: true },
mcode: {
label: 'MiniMax Code',
apiFormat: 'openai_chat',
modelRequired: true,
},
kimi: { label: 'Kimi Code', apiFormat: 'openai_chat', modelRequired: true },
dsh: {
label: 'DeepSeek Harness',
apiFormat: 'openai_chat',
modelRequired: true,
},
omp: { label: 'Oh My Pi', apiFormat: 'openai_chat', modelRequired: true },
copilot: {
label: 'GitHub Copilot CLI',
apiFormat: 'openai_chat',
modelRequired: true,
},
workbuddy: {
label: 'WorkBuddy',
apiFormat: 'openai_chat',
modelRequired: true,
},
zcode: { label: 'ZCode', apiFormat: 'openai_chat', modelRequired: true },
} as const satisfies Record<string, ProviderConfig>
export type CCSwitchApp = keyof typeof CC_SWITCH_APPS
export type CCSwitchModelField =
| 'model'
| 'haikuModel'
| 'sonnetModel'
| 'opusModel'
export function getCCSwitchAddress(address: string): string | null {
let url: URL
try {
url = new URL(address.trim())
} catch {
return null
}
// CC Switch interprets commas as separators between alternative endpoints.
if (
url.username ||
url.password ||
url.search ||
url.hash ||
url.href.includes(',')
) {
return null
}
const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)
if (url.protocol !== 'https:' && !(loopback && url.protocol === 'http:')) {
return null
}
const path = url.pathname.replace(/\/+$/, '').replace(/\/v1(?:beta)?$/, '')
return `${url.origin}${path}`
}
export function buildCCSwitchLink(
app: CCSwitchApp,
name: string,
address: string,
apiKey: string,
models: Partial<Record<CCSwitchModelField, string>>
): string {
const { apiFormat } = CC_SWITCH_APPS[app]
let endpoint = apiFormat.startsWith('openai_') ? `${address}/v1` : address
if (app === 'workbuddy') endpoint += '/chat/completions'
const params = new URLSearchParams({
resource: 'provider',
app,
name: name.trim(),
apiFormat,
endpoint,
apiKey: apiKey.startsWith('sk-') ? apiKey : `sk-${apiKey}`,
homepage: address,
})
const supportedFields: CCSwitchModelField[] =
app === 'claude' || app === 'claude-desktop'
? ['model', 'haikuModel', 'sonnetModel', 'opusModel']
: ['model']
for (const field of supportedFields) {
const model = models[field]?.trim()
if (model) params.set(field, model)
}
return `ccswitch://v1/import?${params}`
}
@@ -196,6 +196,68 @@ it('submits an account ticket with a description as its only text field', async
})
})
it('submits a content report using the dedicated category', async () => {
vi.spyOn(api, 'get').mockResolvedValue(listResponse([], 0))
const post = vi.spyOn(api, 'post').mockResolvedValue({
data: { success: true, data: { ...ticket, category: 'report' } },
})
const user = userEvent.setup()
await renderList('/support-tickets')
const dialog = await openTicketForm(user)
await user.click(dialog.getByRole('combobox', { name: 'Category' }))
await user.click(
await screen.findByRole('option', { name: 'Content report' })
)
await user.type(
dialog.getByRole('textbox', { name: 'Issue description' }),
'Generated content impersonates me without consent'
)
await user.click(dialog.getByRole('button', { name: 'Create ticket' }))
expect(
await screen.findByRole('heading', { name: 'Opened ticket' })
).toBeVisible()
expect(post).toHaveBeenCalledWith('/api/support-tickets', {
category: 'report',
body: 'Generated content impersonates me without consent',
request_id: '',
})
})
it('filters administrator tickets by the content report category', async () => {
const report = {
...ticket,
category: 'report',
subject: 'Content complaint',
} as const
const get = vi
.spyOn(api, 'get')
.mockResolvedValueOnce(listResponse([ticket, report], 2))
.mockResolvedValue(listResponse([report], 1))
const user = userEvent.setup()
await renderList('/admin/support-tickets', 'admin')
expect(
await screen.findByRole('link', { name: ticket.subject })
).toBeVisible()
await user.click(screen.getByRole('combobox', { name: 'Filter by category' }))
await user.click(
await screen.findByRole('option', { name: 'Content report' })
)
await waitFor(() =>
expect(screen.queryByRole('link', { name: ticket.subject })).toBeNull()
)
expect(screen.getByRole('link', { name: report.subject })).toBeVisible()
expect(get).toHaveBeenLastCalledWith(
'/api/admin/support-tickets',
expect.objectContaining({
params: expect.objectContaining({ category: 'report' }),
})
)
})
it('opens the log picker from the keyboard and submits the exact request from an older page', async () => {
const olderRequest: TicketRequest = {
request_id: 'req:17.1',
@@ -24,6 +24,7 @@ export function ticketCategoryOptions(t: TFunction) {
{ value: 'account', label: t('Account') },
{ value: 'payment', label: t('Payment') },
{ value: 'feature_request', label: t('Feature request') },
{ value: 'report', label: t('Content report') },
{ value: 'other', label: t('Other') },
] as const
}
@@ -3,6 +3,7 @@ export const ticketCategories = [
'account',
'payment',
'feature_request',
'report',
'other',
] as const
@@ -88,7 +88,6 @@ const defaultBillingSettings: BillingSettings = {
CreemWebhookSecret: '',
CreemTestMode: false,
CreemProducts: '[]',
WaffoEnabled: false,
WaffoApiKey: '',
WaffoPrivateKey: '',
WaffoPublicCert: '',
@@ -161,7 +161,6 @@ const BILLING_SECTIONS = [
CreemProducts: settings.CreemProducts,
}}
waffoDefaultValues={{
WaffoEnabled: settings.WaffoEnabled ?? false,
WaffoApiKey: settings.WaffoApiKey ?? '',
WaffoPrivateKey: settings.WaffoPrivateKey ?? '',
WaffoPublicCert: settings.WaffoPublicCert ?? '',
@@ -20,7 +20,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useState, type ComponentProps } from 'react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { ALIPAY_ADMIN_PATH } from '@/features/wallet/alipay-direct-api'
import { api } from '@/lib/api'
@@ -31,6 +31,21 @@ import { PaymentSettingsSection } from '../payment-settings-section'
type PaymentProps = ComponentProps<typeof PaymentSettingsSection>
type PaymentValues = PaymentProps['defaultValues']
const GATEWAYS_PATH = '/api/option/payment-gateways'
const gatewayTabs = [
['Epay', 'epay'],
['Stripe', 'stripe'],
['Creem', 'creem'],
['Waffo', 'waffo'],
['Waffo Pancake', 'waffo_pancake'],
] as const
const emptyGateways = Object.fromEntries(
gatewayTabs.map(([, gateway]) => [
gateway,
{ enabled: false, configured: false },
])
)
const defaults: PaymentValues = {
PayAddress: 'https://pay.example.com',
EpayId: '1001',
@@ -64,7 +79,6 @@ function PaymentFixture(props: { values: PaymentValues }) {
<PaymentSettingsSection
defaultValues={props.values}
waffoDefaultValues={{
WaffoEnabled: false,
WaffoApiKey: '',
WaffoPrivateKey: '',
WaffoPublicCert: '',
@@ -110,8 +124,182 @@ async function openEpayTab(values: Partial<PaymentValues> = {}) {
return user
}
beforeEach(() => {
vi.spyOn(api, 'get').mockResolvedValue({
data: { success: true, data: emptyGateways },
})
})
afterEach(() => vi.restoreAllMocks())
describe('payment gateway lifecycle', () => {
it.each(gatewayTabs)(
'stops %s immediately and waits for the saved state',
async (tab, gateway) => {
let enabled = true
let returnStatus!: (value: unknown) => void
const nextStatus = new Promise((resolve) => {
returnStatus = resolve
})
vi.mocked(api.get).mockImplementation(async () => {
if (!enabled) await nextStatus
return {
data: {
success: true,
data: {
...emptyGateways,
[gateway]: { enabled, configured: true },
},
},
}
})
const request = vi.spyOn(api, 'put').mockImplementation(async () => {
enabled = false
return { data: { success: true } }
})
const remove = vi.spyOn(api, 'delete')
const user = await openEpayTab()
await user.click(screen.getByRole('tab', { name: tab }))
const stop = await screen.findByRole('button', { name: 'Stop' })
expect(screen.getByRole('status')).toHaveTextContent('Active')
expect(
screen.getByRole('button', { name: 'Clear configuration' })
).toBeDisabled()
await user.click(stop)
expect(request).toHaveBeenCalledExactlyOnceWith(
`${GATEWAYS_PATH}/${gateway}`,
{ enabled: false }
)
expect(remove).not.toHaveBeenCalled()
expect(stop).toBeDisabled()
expect(screen.getByRole('status')).toHaveTextContent('Active')
returnStatus(undefined)
expect(
await screen.findByRole('button', { name: 'Enable' })
).toBeEnabled()
expect(screen.getByRole('status')).toHaveTextContent('Stopped')
}
)
it('leaves Stop available when an enabled gateway has incomplete configuration', async () => {
vi.mocked(api.get).mockResolvedValue({
data: {
success: true,
data: { ...emptyGateways, epay: { enabled: true, configured: false } },
},
})
await openEpayTab()
expect(await screen.findByRole('button', { name: 'Stop' })).toBeEnabled()
expect(screen.getByRole('status')).toHaveTextContent(
'Payment gateway configuration is incomplete'
)
expect(
screen.getByRole('button', { name: 'Clear configuration' })
).toBeDisabled()
})
it('enables a stopped gateway independently of unsaved form edits', async () => {
let enabled = false
vi.mocked(api.get).mockImplementation(async () => ({
data: {
success: true,
data: {
...emptyGateways,
epay: { enabled, configured: true },
},
},
}))
const request = vi.spyOn(api, 'put').mockImplementation(async () => {
enabled = true
return { data: { success: true } }
})
const user = await openEpayTab()
const secret = screen.getByLabelText('Epay secret key')
await user.type(secret, 'unsaved-secret')
await user.click(await screen.findByRole('button', { name: 'Enable' }))
expect(await screen.findByRole('button', { name: 'Stop' })).toBeEnabled()
expect(request).toHaveBeenCalledExactlyOnceWith(`${GATEWAYS_PATH}/epay`, {
enabled: true,
})
expect(secret).toHaveValue('unsaved-secret')
})
it('clears a stopped gateway only after confirmation and refreshes its availability', async () => {
let configured = true
vi.mocked(api.get).mockImplementation(async () => ({
data: {
success: true,
data: {
...emptyGateways,
epay: { enabled: false, configured },
},
},
}))
const request = vi.spyOn(api, 'delete').mockImplementation(async () => {
configured = false
return { data: { success: true } }
})
const user = await openEpayTab()
const clear = await screen.findByRole('button', {
name: 'Clear configuration',
})
await user.type(screen.getByLabelText('Epay secret key'), 'unsaved-secret')
clear.focus()
await user.keyboard('{Enter}')
let dialog = screen.getByRole('alertdialog')
await user.click(within(dialog).getByRole('button', { name: 'Cancel' }))
expect(request).not.toHaveBeenCalled()
await waitFor(() => expect(clear).toHaveFocus())
await user.click(clear)
dialog = screen.getByRole('alertdialog')
await user.click(
within(dialog).getByRole('button', { name: 'Clear configuration' })
)
await waitFor(() =>
expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()
)
expect(request).toHaveBeenCalledExactlyOnceWith(`${GATEWAYS_PATH}/epay`)
expect(screen.getByRole('status')).toHaveTextContent('Not configured')
expect(screen.getByRole('button', { name: 'Enable' })).toBeDisabled()
expect(screen.getByLabelText('Epay secret key')).toHaveValue('')
})
it('keeps the clear dialog and stopped status when the server rejects the deletion', async () => {
vi.mocked(api.get).mockResolvedValue({
data: {
success: true,
data: {
...emptyGateways,
epay: { enabled: false, configured: true },
},
},
})
const request = vi.spyOn(api, 'delete').mockResolvedValue({
data: {
success: false,
message_key:
'Stop the payment gateway before clearing its configuration',
},
})
const user = await openEpayTab()
await user.click(
await screen.findByRole('button', { name: 'Clear configuration' })
)
const clear = within(screen.getByRole('alertdialog')).getByRole('button', {
name: 'Clear configuration',
})
await user.click(clear)
expect(request).toHaveBeenCalledExactlyOnceWith(`${GATEWAYS_PATH}/epay`)
await waitFor(() => expect(clear).toBeEnabled())
await user.click(
within(screen.getByRole('alertdialog')).getByRole('button', {
name: 'Cancel',
})
)
expect(screen.getByRole('status')).toHaveTextContent('Stopped')
})
})
describe('Epay signature type', () => {
it('shows only the MD5 secret by default and only the RSA keys after choosing RSA', async () => {
const user = await openEpayTab()
@@ -181,9 +369,11 @@ describe('Epay signature type', () => {
expect(
screen.getByRole('textbox', { name: 'Merchant private key' })
).toHaveValue('')
expect(
screen.getByRole('textbox', { name: 'Platform public key' })
).toHaveValue('saved-platform-public-key')
const publicKey = screen.getByRole('textbox', {
name: 'Platform public key',
})
expect(publicKey).toHaveValue('saved-platform-public-key')
await user.clear(publicKey)
await user.click(screen.getByRole('combobox', { name: 'Signature type' }))
await user.click(screen.getByRole('option', { name: 'MD5' }))
@@ -277,7 +467,10 @@ async function openAlipayTab(
| 'archived'
| 'deleted' = () => 'active'
) {
vi.spyOn(api, 'get').mockImplementation(async (url, config) => {
vi.mocked(api.get).mockImplementation(async (url, config) => {
if (url === GATEWAYS_PATH) {
return { data: { success: true, data: emptyGateways } }
}
if (url === `${ALIPAY_ADMIN_PATH}/orders`) {
const params = config?.params as
| { trade_no?: string; merchant_id?: number }
@@ -91,7 +91,7 @@ function GatewayForm(props: { config: Configuration }) {
<Alert>
<AlertDescription>
{t(
'Configure ALIPAY_DIRECT_KEY on the server before enabling Alipay.'
'Configure PAYMENT_CREDENTIAL_KEY on the server before enabling Alipay.'
)}
</AlertDescription>
</Alert>
@@ -0,0 +1,146 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { ConfirmDialog } from '@/components/confirm-dialog'
import { ErrorState } from '@/components/error-state'
import { LoadingState } from '@/components/loading-state'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { SettingsControlGroup } from '../components/settings-form-layout'
import type {
Gateway,
usePaymentGatewayLifecycle,
} from './use-payment-gateway-lifecycle'
export function PaymentGatewayLifecycle(props: {
gateway: Gateway
lifecycle: ReturnType<typeof usePaymentGatewayLifecycle>
isSaving: boolean
canEnable: boolean
}) {
const { t } = useTranslation()
const [confirmClear, setConfirmClear] = useState(false)
const clearButton = useRef<HTMLButtonElement>(null)
const { status, change } = props.lifecycle
const gateway = status.data?.[props.gateway]
const busy = props.isSaving || change.isPending
if (status.isError) {
return (
<ErrorState
className='mb-4 min-h-0 py-4'
title={t('Failed to load payment gateway status')}
onRetry={() => void status.refetch()}
/>
)
}
if (!gateway) {
return (
<SettingsControlGroup className='mb-4' role='status'>
<LoadingState inline size='sm' message={t('Loading...')} />
</SettingsControlGroup>
)
}
const active = gateway.enabled && gateway.configured && props.canEnable
let stateLabel = t('Not configured')
if (active) {
stateLabel = t('Active')
} else if (gateway.enabled) {
stateLabel = gateway.configured
? t('Payment gateway is unavailable')
: t('Payment gateway configuration is incomplete')
} else if (gateway.configured) {
stateLabel = t('Stopped')
}
return (
<SettingsControlGroup className='mb-4'>
<div className='flex flex-wrap items-center justify-between gap-3'>
<div className='flex flex-wrap items-center gap-2' role='status'>
<span className='font-medium'>{t('Payment gateway status')}</span>
<Badge variant={active ? 'default' : 'secondary'}>{stateLabel}</Badge>
</div>
<div className='flex flex-wrap items-center gap-2'>
<Button
type='button'
variant='outline'
size='sm'
disabled={
busy ||
(!gateway.enabled && (!gateway.configured || !props.canEnable))
}
onClick={() =>
change.mutate({
kind: 'set-enabled',
gateway: props.gateway,
enabled: !gateway.enabled,
})
}
>
{gateway.enabled ? t('Stop') : t('Enable')}
</Button>
<Button
ref={clearButton}
type='button'
variant='destructive'
size='sm'
aria-haspopup='dialog'
disabled={busy || gateway.enabled}
onClick={() => setConfirmClear(true)}
>
{t('Clear configuration')}
</Button>
</div>
</div>
{active && (
<p className='text-muted-foreground text-sm'>
{t(
'Changing gateway credentials or routing settings stops new payments until you enable the gateway again.'
)}
</p>
)}
<ConfirmDialog
open={confirmClear}
onOpenChange={(open) => {
if (!change.isPending) setConfirmClear(open)
}}
title={t('Clear payment gateway configuration?')}
desc={t(
'This clears the gateway configuration for future payments and discards unsaved payment settings. Credentials needed for existing orders are retained.'
)}
destructive
confirmText={t('Clear configuration')}
finalFocus={clearButton}
disabled={props.isSaving || gateway.enabled}
isLoading={change.isPending}
handleConfirm={() =>
change.mutate(
{ kind: 'clear', gateway: props.gateway },
{ onSuccess: () => setConfirmClear(false) }
)
}
/>
</SettingsControlGroup>
)
}
@@ -78,7 +78,13 @@ import {
mergeEpayChannels,
validateEpayChannels,
} from './epay-channels'
import { PaymentGatewayLifecycle } from './payment-gateway-lifecycle'
import { PaymentMethodsVisualEditor } from './payment-methods-visual-editor'
import {
paymentGatewayStatusKey,
usePaymentGatewayLifecycle,
type Gateway,
} from './use-payment-gateway-lifecycle'
import {
formatJsonForEditor,
getJsonError,
@@ -198,7 +204,6 @@ const paymentSchema = z.object({
})
}
}),
WaffoEnabled: z.boolean(),
WaffoApiKey: z.string(),
WaffoPrivateKey: z.string(),
WaffoPublicCert: z.string(),
@@ -285,7 +290,13 @@ export function PaymentSettingsSection({
[initialFormValues]
)
const [paymentTab, setPaymentTab] = React.useState('general')
const [paymentTab, setPaymentTab] = React.useState<
Gateway | 'general' | 'alipay-direct'
>('general')
const [clearRevision, setClearRevision] = React.useState(0)
const lifecycle = usePaymentGatewayLifecycle(() =>
setClearRevision((revision) => revision + 1)
)
const [payMethodsVisualMode, setPayMethodsVisualMode] = React.useState(true)
const [amountOptionsVisualMode, setAmountOptionsVisualMode] =
React.useState(true)
@@ -310,7 +321,7 @@ export function PaymentSettingsSection({
React.useEffect(() => {
setWaffoPayMethods(parseWaffoPayMethods(waffoDefaultValues.WaffoPayMethods))
}, [waffoDefaultValues.WaffoPayMethods])
}, [clearRevision, waffoDefaultValues.WaffoPayMethods])
React.useEffect(() => {
const nextBinding = {
@@ -319,7 +330,11 @@ export function PaymentSettingsSection({
}
setWaffoPancakeSelection(nextBinding)
setWaffoPancakeSavedBinding(nextBinding)
}, [waffoPancakeProvisionedProductID, waffoPancakeProvisionedStoreID])
}, [
clearRevision,
waffoPancakeProvisionedProductID,
waffoPancakeProvisionedStoreID,
])
const complianceStatements = React.useMemo(
() => [
@@ -462,9 +477,9 @@ export function PaymentSettingsSection({
AmountDiscount: formatJsonForEditor(parsedDefaults.AmountDiscount),
CreemProducts: formatJsonForEditor(parsedDefaults.CreemProducts),
})
}, [defaultsSignature, form])
}, [clearRevision, defaultsSignature, form])
const onSubmit = async (values: PaymentFormValues) => {
const saveSettings = async (values: PaymentFormValues) => {
const sanitized = {
CustomAmount: JSON.stringify(values.CustomAmount),
PayAddress: removeTrailingSlash(values.PayAddress),
@@ -492,7 +507,6 @@ export function PaymentSettingsSection({
CreemWebhookSecret: values.CreemWebhookSecret.trim(),
CreemTestMode: values.CreemTestMode,
CreemProducts: values.CreemProducts.trim(),
WaffoEnabled: values.WaffoEnabled,
WaffoSandbox: values.WaffoSandbox,
WaffoMerchantId: values.WaffoMerchantId.trim(),
WaffoCurrency: values.WaffoCurrency.trim() || 'USD',
@@ -540,7 +554,6 @@ export function PaymentSettingsSection({
CreemWebhookSecret: initialRef.current.CreemWebhookSecret.trim(),
CreemTestMode: initialRef.current.CreemTestMode,
CreemProducts: initialRef.current.CreemProducts.trim(),
WaffoEnabled: initialRef.current.WaffoEnabled,
WaffoSandbox: initialRef.current.WaffoSandbox,
WaffoMerchantId: initialRef.current.WaffoMerchantId.trim(),
WaffoCurrency: initialRef.current.WaffoCurrency.trim() || 'USD',
@@ -589,7 +602,10 @@ export function PaymentSettingsSection({
})
}
if (sanitized.EpayPlatformPublicKey !== initial.EpayPlatformPublicKey) {
if (
sanitized.EpayPlatformPublicKey &&
sanitized.EpayPlatformPublicKey !== initial.EpayPlatformPublicKey
) {
updates.push({
key: 'payment_setting.epay_platform_public_key',
value: sanitized.EpayPlatformPublicKey,
@@ -721,10 +737,6 @@ export function PaymentSettingsSection({
updates.push({ key: 'CreemProducts', value: sanitized.CreemProducts })
}
if (sanitized.WaffoEnabled !== initial.WaffoEnabled) {
updates.push({ key: 'WaffoEnabled', value: sanitized.WaffoEnabled })
}
if (sanitized.WaffoSandbox !== initial.WaffoSandbox) {
updates.push({ key: 'WaffoSandbox', value: sanitized.WaffoSandbox })
}
@@ -753,11 +765,11 @@ export function PaymentSettingsSection({
updates.push({ key: 'WaffoReturnUrl', value: sanitized.WaffoReturnUrl })
}
if (sanitized.WaffoPublicCert !== initial.WaffoPublicCert) {
if (sanitized.WaffoPublicCert) {
updates.push({ key: 'WaffoPublicCert', value: sanitized.WaffoPublicCert })
}
if (sanitized.WaffoSandboxPublicCert !== initial.WaffoSandboxPublicCert) {
if (sanitized.WaffoSandboxPublicCert) {
updates.push({
key: 'WaffoSandboxPublicCert',
value: sanitized.WaffoSandboxPublicCert,
@@ -867,9 +879,17 @@ export function PaymentSettingsSection({
}
}
const onSubmit = async (values: PaymentFormValues) => {
if (lifecycle.change.isPending) return
try {
await saveSettings(values)
} finally {
await queryClient.invalidateQueries({ queryKey: paymentGatewayStatusKey })
}
}
const currentFormValues = form.watch()
const waffoValues: WaffoSettingsValues = {
WaffoEnabled: currentFormValues.WaffoEnabled,
WaffoApiKey: currentFormValues.WaffoApiKey,
WaffoPrivateKey: currentFormValues.WaffoPrivateKey,
WaffoPublicCert: currentFormValues.WaffoPublicCert,
@@ -970,10 +990,19 @@ export function PaymentSettingsSection({
<TabsTrigger value='epay'>Epay</TabsTrigger>
<TabsTrigger value='stripe'>{t('Stripe')}</TabsTrigger>
<TabsTrigger value='creem'>Creem</TabsTrigger>
<TabsTrigger value='waffo-pancake'>Waffo Pancake</TabsTrigger>
<TabsTrigger value='waffo_pancake'>Waffo Pancake</TabsTrigger>
<TabsTrigger value='waffo'>Waffo</TabsTrigger>
</TabsList>
</div>
{paymentTab !== 'general' && paymentTab !== 'alipay-direct' && (
<PaymentGatewayLifecycle
key={paymentTab}
gateway={paymentTab}
lifecycle={lifecycle}
isSaving={updateOption.isPending || isSubmitting}
canEnable={complianceConfirmed}
/>
)}
<Form {...form}>
<SettingsForm
onSubmit={form.handleSubmit(onSubmit)}
@@ -987,6 +1016,7 @@ export function PaymentSettingsSection({
<SettingsPageFormActions
onSave={form.handleSubmit(onSubmit)}
isSaving={updateOption.isPending || isSubmitting}
isSaveDisabled={lifecycle.change.isPending}
saveLabel='Save all settings'
/>
)}
@@ -1874,10 +1904,11 @@ export function PaymentSettingsSection({
</TabsContent>
<TabsContent
value='waffo-pancake'
value='waffo_pancake'
className={paymentTabContentClassName}
>
<WaffoPancakeSettingsSection
key={clearRevision}
defaultValues={waffoPancakeDefaultValues}
values={waffoPancakeValues}
onValueChange={setWaffoPancakeValue}
@@ -0,0 +1,75 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { api } from '@/lib/api'
import { handleServerError } from '@/lib/handle-server-error'
import { requireServerSuccess } from '@/lib/server-error-message'
import type { UpdateOptionResponse } from '../types'
const GATEWAYS_PATH = '/api/option/payment-gateways'
export const paymentGatewayStatusKey = ['payment-gateways'] as const
export type Gateway = 'epay' | 'stripe' | 'creem' | 'waffo' | 'waffo_pancake'
type GatewayState = { enabled: boolean; configured: boolean }
type GatewayAction = { gateway: Gateway } & (
| { kind: 'set-enabled'; enabled: boolean }
| { kind: 'clear' }
)
export function usePaymentGatewayLifecycle(onCleared: () => void) {
const { t } = useTranslation()
const queryClient = useQueryClient()
const status = useQuery({
queryKey: paymentGatewayStatusKey,
queryFn: async ({ signal }) => {
const response = await api.get<
UpdateOptionResponse & { data: Record<Gateway, GatewayState> }
>(GATEWAYS_PATH, { signal, disableDuplicate: true })
return requireServerSuccess(response.data).data
},
meta: { errorToast: false },
})
const change = useMutation({
mutationFn: async (action: GatewayAction) => {
const path = `${GATEWAYS_PATH}/${action.gateway}`
const response =
action.kind === 'clear'
? await api.delete<UpdateOptionResponse>(path)
: await api.put<UpdateOptionResponse>(path, {
enabled: action.enabled,
})
return requireServerSuccess(response.data)
},
onSuccess: async (_, action) => {
if (action.kind === 'clear') {
await queryClient.invalidateQueries({ queryKey: ['system-options'] })
onCleared()
}
},
onSettled: async () => {
await queryClient.invalidateQueries({ queryKey: paymentGatewayStatusKey })
},
onError: (error) => handleServerError(error, t('Failed to update setting')),
})
return { status, change }
}
@@ -34,7 +34,6 @@ import { Textarea } from '@/components/ui/textarea'
import { SettingsSwitchField } from '../components/settings-form-layout'
export interface WaffoSettingsValues {
WaffoEnabled: boolean
WaffoApiKey: string
WaffoPrivateKey: string
WaffoPublicCert: string
@@ -161,12 +160,6 @@ export function WaffoSettingsSection({
</Alert>
<div className='grid gap-4 sm:grid-cols-2'>
<SettingsSwitchField
checked={values.WaffoEnabled}
onCheckedChange={(v) => onValueChange('WaffoEnabled', v)}
label={t('Enable Waffo')}
className='py-0'
/>
<SettingsSwitchField
checked={values.WaffoSandbox}
onCheckedChange={(v) => onValueChange('WaffoSandbox', v)}
@@ -333,7 +333,6 @@ export type BillingSettings = {
CreemWebhookSecret: string
CreemTestMode: boolean
CreemProducts: string
WaffoEnabled: boolean
WaffoApiKey: string
WaffoPrivateKey: string
WaffoPublicCert: string
@@ -0,0 +1,114 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { afterEach, expect, it, vi } from 'vitest'
import type { PlanRecord } from '@/features/subscriptions/types'
import { api } from '@/lib/api'
import { SubscriptionPlansCard } from '../components/subscription-plans-card'
import type { TopupInfo } from '../types'
const plan: PlanRecord = {
plan: {
id: 1,
title: 'Monthly plan',
price_amount: 10,
currency: 'USD',
duration_unit: 'month',
duration_value: 1,
quota_reset_period: 'never',
enabled: true,
sort_order: 0,
allow_balance_pay: false,
allow_wallet_overflow: false,
max_purchase_per_user: 0,
total_amount: 500000,
stripe_price_id: 'price_plan',
creem_product_id: 'creem_plan',
waffo_pancake_product_id: 'pancake_plan',
},
}
const topupInfo: TopupInfo = {
enable_online_topup: false,
enable_stripe_topup: true,
enable_creem_topup: true,
enable_waffo_pancake_topup: true,
pay_methods: [],
min_topup: 1,
stripe_min_topup: 1,
amount_options: [],
discount: {},
}
async function openSubscriptionCheckout(info: TopupInfo) {
vi.spyOn(api, 'get').mockImplementation(async (url) => {
if (url === '/api/subscription/plans') {
return { data: { success: true, data: [plan] } }
}
if (url === '/api/subscription/self') {
return {
data: {
success: true,
data: { subscriptions: [], all_subscriptions: [] },
},
}
}
throw new Error(`Unexpected request: ${url}`)
})
const client = new QueryClient({
defaultOptions: { queries: { retry: false } },
})
render(
<QueryClientProvider client={client}>
<SubscriptionPlansCard topupInfo={info} />
</QueryClientProvider>
)
const user = userEvent.setup()
await user.click(await screen.findByRole('button', { name: 'Subscribe Now' }))
return within(screen.getByRole('dialog'))
}
afterEach(() => vi.restoreAllMocks())
it('uses subscription flags for plan checkout even when wallet top-up availability differs', async () => {
const checkout = await openSubscriptionCheckout({
...topupInfo,
enable_stripe_topup: false,
enable_stripe_subscription: true,
enable_creem_subscription: false,
enable_waffo_pancake_topup: false,
enable_waffo_pancake_subscription: true,
})
expect(checkout.getByRole('button', { name: 'Stripe' })).toBeVisible()
expect(
checkout.queryByRole('button', { name: 'Creem' })
).not.toBeInTheDocument()
expect(checkout.getByRole('button', { name: 'Waffo Pancake' })).toBeVisible()
})
it('uses the older top-up flags when subscription flags are absent', async () => {
const checkout = await openSubscriptionCheckout(topupInfo)
for (const name of ['Stripe', 'Creem', 'Waffo Pancake']) {
expect(checkout.getByRole('button', { name })).toBeVisible()
}
})
@@ -115,9 +115,13 @@ export function SubscriptionPlansCard({
const [purchaseOpen, setPurchaseOpen] = useState(false)
const [selectedPlan, setSelectedPlan] = useState<PlanRecord | null>(null)
const enableStripe = !!topupInfo?.enable_stripe_topup
const enableCreem = !!topupInfo?.enable_creem_topup
const enableWaffoPancake = !!topupInfo?.enable_waffo_pancake_topup
const enableStripe =
topupInfo?.enable_stripe_subscription ?? topupInfo?.enable_stripe_topup
const enableCreem =
topupInfo?.enable_creem_subscription ?? topupInfo?.enable_creem_topup
const enableWaffoPancake =
topupInfo?.enable_waffo_pancake_subscription ??
topupInfo?.enable_waffo_pancake_topup
const enableOnlineTopUp = !!topupInfo?.enable_online_topup
const epayMethods = topupInfo?.epay_pay_methods
+3
View File
@@ -124,6 +124,9 @@ export interface TopupInfo {
enable_online_topup: boolean
/** Whether Stripe topup is enabled */
enable_stripe_topup: boolean
enable_stripe_subscription?: boolean
enable_creem_subscription?: boolean
enable_waffo_pancake_subscription?: boolean
/** Available payment methods */
pay_methods: PaymentMethod[]
epay_pay_methods?: PaymentMethod[]
+18 -2
View File
@@ -1626,6 +1626,7 @@
"Category name must be less than 50 characters": "Category name must be less than 50 characters",
"Caution": "Caution",
"CC Switch": "CC Switch",
"CC Switch import requires an HTTPS server address or a local loopback address.": "CC Switch import requires an HTTPS server address or a local loopback address.",
"Centered": "Centered",
"Chain": "Chain",
"Change": "Change",
@@ -8732,6 +8733,7 @@
"Use authenticator code": "Use authenticator code",
"Use backup code": "Use backup code",
"Use Bearer for all protocols": "Use Bearer for all protocols",
"Use CC Switch v4.0.47 or later to confirm the import.": "Use CC Switch v4.0.47 or later to confirm the import.",
"Use channel type {{type}}": "Use channel type {{type}}",
"Use default": "Use default",
"Use disk cache when request body exceeds this size": "Use disk cache when request body exceeds this size",
@@ -9569,6 +9571,7 @@
"Review and respond to user support tickets.": "Review and respond to user support tickets.",
"API error": "API error",
"Feature request": "Feature request",
"Content report": "Content report",
"Waiting for support": "Waiting for support",
"Waiting for user": "Waiting for user",
"All statuses": "All statuses",
@@ -9690,7 +9693,19 @@
"Checkout expired. Refresh the order status before paying again.": "Checkout expired. Refresh the order status before paying again.",
"Checkout is unavailable. Retry to continue the same order.": "Checkout is unavailable. Retry to continue the same order.",
"Checkout mode": "Checkout mode",
"Configure ALIPAY_DIRECT_KEY on the server before enabling Alipay.": "Configure ALIPAY_DIRECT_KEY on the server before enabling Alipay.",
"Configure PAYMENT_CREDENTIAL_KEY on the server before enabling Alipay.": "Configure PAYMENT_CREDENTIAL_KEY on the server before enabling Alipay.",
"Payment gateway status": "Payment gateway status",
"Stopped": "Stopped",
"Clear configuration": "Clear configuration",
"Clear payment gateway configuration?": "Clear payment gateway configuration?",
"This clears the gateway configuration for future payments and discards unsaved payment settings. Credentials needed for existing orders are retained.": "This clears the gateway configuration for future payments and discards unsaved payment settings. Credentials needed for existing orders are retained.",
"Changing gateway credentials or routing settings stops new payments until you enable the gateway again.": "Changing gateway credentials or routing settings stops new payments until you enable the gateway again.",
"Failed to load payment gateway status": "Failed to load payment gateway status",
"Payment gateway is unavailable": "Payment gateway is unavailable",
"Payment gateway configuration is incomplete": "Payment gateway configuration is incomplete",
"Stop the payment gateway before clearing its configuration": "Stop the payment gateway before clearing its configuration",
"Payment gateway configuration changed. Try again.": "Payment gateway configuration changed. Try again.",
"Payment gateway validation failed": "Payment gateway validation failed",
"Confirm that the merchant is approved for embedded checkout.": "Confirm that the merchant is approved for embedded checkout.",
"Could not get a payment quote.": "Could not get a payment quote.",
"Disable Alipay merchant": "Disable Alipay merchant",
@@ -9742,7 +9757,8 @@
"Verified provider callback": "Verified provider callback",
"Verified provider query": "Verified provider query",
"Zero means no limit.": "Zero means no limit.",
"ALIPAY_DIRECT_KEY must be a base64-encoded 32-byte key": "ALIPAY_DIRECT_KEY must be a base64-encoded 32-byte key",
"PAYMENT_CREDENTIAL_KEY must be a separate base64-encoded 32-byte key": "PAYMENT_CREDENTIAL_KEY must be a separate base64-encoded 32-byte key",
"Save payment credentials separately from passkey domains": "Save payment credentials separately from passkey domains",
"No Alipay merchant is available for this order": "No Alipay merchant is available for this order",
"Alipay order conflicts with an existing request": "Alipay order conflicts with an existing request",
"Invalid Alipay order": "Invalid Alipay order",
+18 -2
View File
@@ -1626,6 +1626,7 @@
"Category name must be less than 50 characters": "Le nom de la catégorie doit contenir moins de 50 caractères",
"Caution": "Attention",
"CC Switch": "CC Switch",
"CC Switch import requires an HTTPS server address or a local loopback address.": "L’importation dans CC Switch nécessite une adresse de serveur HTTPS ou une adresse de bouclage locale.",
"Centered": "Centré",
"Chain": "Chaîne",
"Change": "Modifier",
@@ -8732,6 +8733,7 @@
"Use authenticator code": "Utiliser le code de l'authentificateur",
"Use backup code": "Utiliser un code de secours",
"Use Bearer for all protocols": "Utiliser Bearer pour tous les protocoles",
"Use CC Switch v4.0.47 or later to confirm the import.": "Utilisez CC Switch v4.0.47 ou une version ultérieure pour confirmer l’importation.",
"Use channel type {{type}}": "Utiliser le type de canal {{type}}",
"Use default": "Utiliser la valeur par défaut",
"Use disk cache when request body exceeds this size": "Utiliser le cache disque quand le corps de requête dépasse cette taille",
@@ -9569,6 +9571,7 @@
"Review and respond to user support tickets.": "Consultez les tickets et répondez aux utilisateurs.",
"API error": "Erreur d’API",
"Feature request": "Demande de fonctionnalité",
"Content report": "Signalement de contenu",
"Waiting for support": "En attente de l’assistance",
"Waiting for user": "En attente de l’utilisateur",
"All statuses": "Tous les statuts",
@@ -9690,7 +9693,19 @@
"Checkout expired. Refresh the order status before paying again.": "Le paiement a expiré. Actualisez la commande avant de payer à nouveau.",
"Checkout is unavailable. Retry to continue the same order.": "Paiement indisponible. Réessayez pour reprendre cette commande.",
"Checkout mode": "Mode de paiement",
"Configure ALIPAY_DIRECT_KEY on the server before enabling Alipay.": "Configurez ALIPAY_DIRECT_KEY sur le serveur avant d’activer Alipay.",
"Configure PAYMENT_CREDENTIAL_KEY on the server before enabling Alipay.": "Configurez PAYMENT_CREDENTIAL_KEY sur le serveur avant d’activer Alipay.",
"Payment gateway status": "État de la passerelle de paiement",
"Stopped": "Arrêtée",
"Clear configuration": "Effacer la configuration",
"Clear payment gateway configuration?": "Effacer la configuration de la passerelle de paiement ?",
"This clears the gateway configuration for future payments and discards unsaved payment settings. Credentials needed for existing orders are retained.": "Cette action efface la configuration de la passerelle pour les futurs paiements et annule les modifications non enregistrées. Les identifiants nécessaires aux commandes existantes sont conservés.",
"Changing gateway credentials or routing settings stops new payments until you enable the gateway again.": "La modification des identifiants ou des paramètres de routage suspend les nouveaux paiements jusqu’à la réactivation de la passerelle.",
"Failed to load payment gateway status": "Impossible de charger l’état de la passerelle de paiement",
"Payment gateway is unavailable": "La passerelle de paiement est indisponible",
"Payment gateway configuration is incomplete": "La configuration de la passerelle de paiement est incomplète",
"Stop the payment gateway before clearing its configuration": "Arrêtez la passerelle de paiement avant d’effacer sa configuration",
"Payment gateway configuration changed. Try again.": "La configuration de la passerelle de paiement a changé. Réessayez.",
"Payment gateway validation failed": "La validation de la passerelle de paiement a échoué",
"Confirm that the merchant is approved for embedded checkout.": "Confirmez que le marchand est autorisé à utiliser le paiement intégré.",
"Could not get a payment quote.": "Impossible d’obtenir le montant à payer.",
"Disable Alipay merchant": "Désactiver le marchand Alipay",
@@ -9742,7 +9757,8 @@
"Verified provider callback": "Notification vérifiée du prestataire",
"Verified provider query": "Interrogation vérifiée du prestataire",
"Zero means no limit.": "Zéro signifie sans limite.",
"ALIPAY_DIRECT_KEY must be a base64-encoded 32-byte key": "ALIPAY_DIRECT_KEY doit contenir une clé de 32 octets encodée en Base64",
"PAYMENT_CREDENTIAL_KEY must be a separate base64-encoded 32-byte key": "PAYMENT_CREDENTIAL_KEY doit être une clé distincte de 32 octets encodée en Base64",
"Save payment credentials separately from passkey domains": "Enregistrez les identifiants de paiement séparément des domaines de clés d’accès",
"No Alipay merchant is available for this order": "Aucun marchand Alipay ne peut traiter cette commande",
"Alipay order conflicts with an existing request": "La commande Alipay entre en conflit avec une demande existante",
"Invalid Alipay order": "Commande Alipay invalide",
+18 -2
View File
@@ -1626,6 +1626,7 @@
"Category name must be less than 50 characters": "カテゴリ名は50文字以内にしてください",
"Caution": "注意",
"CC Switch": "CC Switch",
"CC Switch import requires an HTTPS server address or a local loopback address.": "CC Switch へのインポートには、HTTPS のサーバーアドレスまたはローカルループバックアドレスが必要です。",
"Centered": "中央揃え",
"Chain": "チェーン",
"Change": "変更",
@@ -8732,6 +8733,7 @@
"Use authenticator code": "認証コードを使用",
"Use backup code": "バックアップコードを使用",
"Use Bearer for all protocols": "すべてのプロトコルで Bearer を使用",
"Use CC Switch v4.0.47 or later to confirm the import.": "CC Switch v4.0.47 以降でインポートを確認してください。",
"Use channel type {{type}}": "チャネルタイプ {{type}} を使用",
"Use default": "既定値を使用",
"Use disk cache when request body exceeds this size": "リクエストボディがこのサイズを超えた場合にディスクキャッシュを使用",
@@ -9569,6 +9571,7 @@
"Review and respond to user support tickets.": "ユーザーのサポートチケットを確認して返信します。",
"API error": "API エラー",
"Feature request": "機能の要望",
"Content report": "コンテンツの通報",
"Waiting for support": "サポートの返信待ち",
"Waiting for user": "ユーザーの返信待ち",
"All statuses": "すべてのステータス",
@@ -9690,7 +9693,19 @@
"Checkout expired. Refresh the order status before paying again.": "決済の有効期限が切れました。再度支払う前に注文状況を更新してください。",
"Checkout is unavailable. Retry to continue the same order.": "決済を利用できません。再試行すると同じ注文を続けられます。",
"Checkout mode": "決済方式",
"Configure ALIPAY_DIRECT_KEY on the server before enabling Alipay.": "Alipayを有効にする前にサーバーのALIPAY_DIRECT_KEYを設定してください。",
"Configure PAYMENT_CREDENTIAL_KEY on the server before enabling Alipay.": "Alipayを有効にする前にサーバーのPAYMENT_CREDENTIAL_KEYを設定してください。",
"Payment gateway status": "決済ゲートウェイの状態",
"Stopped": "停止中",
"Clear configuration": "設定を消去",
"Clear payment gateway configuration?": "決済ゲートウェイの設定を消去しますか?",
"This clears the gateway configuration for future payments and discards unsaved payment settings. Credentials needed for existing orders are retained.": "今後の決済に使用するゲートウェイの設定を消去し、未保存の決済設定を破棄します。既存の注文に必要な認証情報は保持されます。",
"Changing gateway credentials or routing settings stops new payments until you enable the gateway again.": "ゲートウェイの認証情報またはルーティング設定を変更すると、ゲートウェイを再度有効にするまで新しい決済が停止します。",
"Failed to load payment gateway status": "決済ゲートウェイの状態を読み込めませんでした",
"Payment gateway is unavailable": "決済ゲートウェイは利用できません",
"Payment gateway configuration is incomplete": "決済ゲートウェイの設定が完了していません",
"Stop the payment gateway before clearing its configuration": "設定を消去する前に、決済ゲートウェイを停止してください",
"Payment gateway configuration changed. Try again.": "決済ゲートウェイの設定が変更されました。もう一度お試しください。",
"Payment gateway validation failed": "決済ゲートウェイの検証に失敗しました",
"Confirm that the merchant is approved for embedded checkout.": "加盟店が埋め込み決済の承認を受けていることを確認してください。",
"Could not get a payment quote.": "支払額を取得できませんでした。",
"Disable Alipay merchant": "Alipay加盟店を無効にする",
@@ -9742,7 +9757,8 @@
"Verified provider callback": "検証済みの事業者コールバック",
"Verified provider query": "検証済みの事業者照会",
"Zero means no limit.": "0は上限なしです。",
"ALIPAY_DIRECT_KEY must be a base64-encoded 32-byte key": "ALIPAY_DIRECT_KEYにはBase64でエンコードした32バイトの鍵が必要です",
"PAYMENT_CREDENTIAL_KEY must be a separate base64-encoded 32-byte key": "PAYMENT_CREDENTIAL_KEY には別の Base64 エンコード済み 32 バイト鍵を指定してください",
"Save payment credentials separately from passkey domains": "決済の認証情報とパスキーのドメインは別々に保存してください",
"No Alipay merchant is available for this order": "この注文を処理できるAlipay加盟店がありません",
"Alipay order conflicts with an existing request": "Alipay注文が既存のリクエストと競合しています",
"Invalid Alipay order": "Alipay注文が無効です",
+18 -2
View File
@@ -1626,6 +1626,7 @@
"Category name must be less than 50 characters": "Название категории должно содержать менее 50 символов",
"Caution": "Внимание",
"CC Switch": "CC Switch",
"CC Switch import requires an HTTPS server address or a local loopback address.": "Для импорта в CC Switch требуется HTTPS-адрес сервера или адрес локальной петли.",
"Centered": "По центру",
"Chain": "Цепочка",
"Change": "Изменить",
@@ -8732,6 +8733,7 @@
"Use authenticator code": "Использовать код аутентификатора",
"Use backup code": "Использовать резервный код",
"Use Bearer for all protocols": "Использовать Bearer для всех протоколов",
"Use CC Switch v4.0.47 or later to confirm the import.": "Подтвердите импорт в CC Switch версии 4.0.47 или новее.",
"Use channel type {{type}}": "Использовать тип канала {{type}}",
"Use default": "Использовать значение по умолчанию",
"Use disk cache when request body exceeds this size": "Использовать дисковый кэш, когда тело запроса превышает этот размер",
@@ -9569,6 +9571,7 @@
"Review and respond to user support tickets.": "Просматривайте обращения пользователей и отвечайте на них.",
"API error": "Ошибка API",
"Feature request": "Предложение по улучшению",
"Content report": "Жалоба на контент",
"Waiting for support": "Ожидает ответа поддержки",
"Waiting for user": "Ожидает ответа пользователя",
"All statuses": "Все статусы",
@@ -9690,7 +9693,19 @@
"Checkout expired. Refresh the order status before paying again.": "Срок оплаты истёк. Обновите статус перед повторной оплатой.",
"Checkout is unavailable. Retry to continue the same order.": "Оплата недоступна. Повторите попытку для того же заказа.",
"Checkout mode": "Режим оплаты",
"Configure ALIPAY_DIRECT_KEY on the server before enabling Alipay.": "Настройте ALIPAY_DIRECT_KEY на сервере перед включением Alipay.",
"Configure PAYMENT_CREDENTIAL_KEY on the server before enabling Alipay.": "Настройте PAYMENT_CREDENTIAL_KEY на сервере перед включением Alipay.",
"Payment gateway status": "Состояние платёжного шлюза",
"Stopped": "Остановлен",
"Clear configuration": "Очистить настройки",
"Clear payment gateway configuration?": "Очистить настройки платёжного шлюза?",
"This clears the gateway configuration for future payments and discards unsaved payment settings. Credentials needed for existing orders are retained.": "Настройки шлюза для будущих платежей и несохранённые изменения будут удалены. Учётные данные, необходимые для существующих заказов, сохранятся.",
"Changing gateway credentials or routing settings stops new payments until you enable the gateway again.": "При изменении учётных данных или маршрутизации новые платежи приостанавливаются до повторного включения шлюза.",
"Failed to load payment gateway status": "Не удалось загрузить состояние платёжного шлюза",
"Payment gateway is unavailable": "Платёжный шлюз недоступен",
"Payment gateway configuration is incomplete": "Настройка платёжного шлюза не завершена",
"Stop the payment gateway before clearing its configuration": "Остановите платёжный шлюз перед очисткой его настроек",
"Payment gateway configuration changed. Try again.": "Настройки платёжного шлюза изменились. Повторите попытку.",
"Payment gateway validation failed": "Не удалось проверить платёжный шлюз",
"Confirm that the merchant is approved for embedded checkout.": "Подтвердите, что продавцу разрешена встроенная оплата.",
"Could not get a payment quote.": "Не удалось получить сумму к оплате.",
"Disable Alipay merchant": "Отключить продавца Alipay",
@@ -9742,7 +9757,8 @@
"Verified provider callback": "Подтверждённое уведомление провайдера",
"Verified provider query": "Подтверждённый запрос к провайдеру",
"Zero means no limit.": "Ноль означает отсутствие лимита.",
"ALIPAY_DIRECT_KEY must be a base64-encoded 32-byte key": "ALIPAY_DIRECT_KEY должен быть 32-байтовым ключом в Base64",
"PAYMENT_CREDENTIAL_KEY must be a separate base64-encoded 32-byte key": "PAYMENT_CREDENTIAL_KEY должен быть отдельным 32-байтовым ключом в Base64",
"Save payment credentials separately from passkey domains": "Сохраните платёжные учётные данные отдельно от доменов ключей доступа",
"No Alipay merchant is available for this order": "Нет продавца Alipay для этого заказа",
"Alipay order conflicts with an existing request": "Заказ Alipay конфликтует с существующим запросом",
"Invalid Alipay order": "Недействительный заказ Alipay",
+18 -2
View File
@@ -1626,6 +1626,7 @@
"Category name must be less than 50 characters": "Tên danh mục phải ít hơn 50 ký tự",
"Caution": "Thận trọng",
"CC Switch": "CC Switch",
"CC Switch import requires an HTTPS server address or a local loopback address.": "Để nhập vào CC Switch, cần địa chỉ máy chủ HTTPS hoặc địa chỉ loopback cục bộ.",
"Centered": "Căn giữa",
"Chain": "Chuỗi",
"Change": "Thay đổi",
@@ -8732,6 +8733,7 @@
"Use authenticator code": "Sử dụng mã xác thực",
"Use backup code": "Sử dụng mã dự phòng",
"Use Bearer for all protocols": "Dùng Bearer cho mọi giao thức",
"Use CC Switch v4.0.47 or later to confirm the import.": "Dùng CC Switch v4.0.47 trở lên để xác nhận nhập.",
"Use channel type {{type}}": "Sử dụng loại kênh {{type}}",
"Use default": "Dùng mặc định",
"Use disk cache when request body exceeds this size": "Sử dụng bộ nhớ đệm đĩa khi nội dung yêu cầu vượt quá kích thước này",
@@ -9569,6 +9571,7 @@
"Review and respond to user support tickets.": "Xem và trả lời yêu cầu hỗ trợ của người dùng.",
"API error": "Lỗi API",
"Feature request": "Đề xuất tính năng",
"Content report": "Báo cáo nội dung",
"Waiting for support": "Đang chờ hỗ trợ",
"Waiting for user": "Đang chờ người dùng",
"All statuses": "Tất cả trạng thái",
@@ -9690,7 +9693,19 @@
"Checkout expired. Refresh the order status before paying again.": "Phiên thanh toán đã hết hạn. Hãy làm mới trạng thái trước khi trả lại.",
"Checkout is unavailable. Retry to continue the same order.": "Không thể mở thanh toán. Thử lại để tiếp tục cùng đơn hàng.",
"Checkout mode": "Hình thức thanh toán",
"Configure ALIPAY_DIRECT_KEY on the server before enabling Alipay.": "Hãy cấu hình ALIPAY_DIRECT_KEY trên máy chủ trước khi bật Alipay.",
"Configure PAYMENT_CREDENTIAL_KEY on the server before enabling Alipay.": "Hãy cấu hình PAYMENT_CREDENTIAL_KEY trên máy chủ trước khi bật Alipay.",
"Payment gateway status": "Trạng thái cổng thanh toán",
"Stopped": "Đã dừng",
"Clear configuration": "Xóa cấu hình",
"Clear payment gateway configuration?": "Xóa cấu hình cổng thanh toán?",
"This clears the gateway configuration for future payments and discards unsaved payment settings. Credentials needed for existing orders are retained.": "Thao tác này xóa cấu hình cổng cho các khoản thanh toán sau này và hủy các thay đổi chưa lưu. Thông tin xác thực cần cho đơn hàng hiện có được giữ lại.",
"Changing gateway credentials or routing settings stops new payments until you enable the gateway again.": "Việc thay đổi thông tin xác thực hoặc cấu hình định tuyến sẽ dừng các khoản thanh toán mới cho đến khi bạn bật lại cổng.",
"Failed to load payment gateway status": "Không thể tải trạng thái cổng thanh toán",
"Payment gateway is unavailable": "Cổng thanh toán không khả dụng",
"Payment gateway configuration is incomplete": "Cấu hình cổng thanh toán chưa hoàn tất",
"Stop the payment gateway before clearing its configuration": "Hãy dừng cổng thanh toán trước khi xóa cấu hình",
"Payment gateway configuration changed. Try again.": "Cấu hình cổng thanh toán đã thay đổi. Hãy thử lại.",
"Payment gateway validation failed": "Xác thực cổng thanh toán thất bại",
"Confirm that the merchant is approved for embedded checkout.": "Xác nhận đơn vị bán hàng được phép dùng thanh toán nhúng.",
"Could not get a payment quote.": "Không thể lấy báo giá thanh toán.",
"Disable Alipay merchant": "Tắt đơn vị bán hàng Alipay",
@@ -9742,7 +9757,8 @@
"Verified provider callback": "Thông báo xác thực từ nhà cung cấp",
"Verified provider query": "Truy vấn xác thực từ nhà cung cấp",
"Zero means no limit.": "0 nghĩa là không giới hạn.",
"ALIPAY_DIRECT_KEY must be a base64-encoded 32-byte key": "ALIPAY_DIRECT_KEY phải là khóa 32 byte mã hóa Base64",
"PAYMENT_CREDENTIAL_KEY must be a separate base64-encoded 32-byte key": "PAYMENT_CREDENTIAL_KEY phải là một khóa riêng 32 byte được mã hóa Base64",
"Save payment credentials separately from passkey domains": "Hãy lưu thông tin xác thực thanh toán riêng với các tên miền khóa truy cập",
"No Alipay merchant is available for this order": "Không có đơn vị bán hàng Alipay cho đơn này",
"Alipay order conflicts with an existing request": "Đơn Alipay xung đột với yêu cầu hiện có",
"Invalid Alipay order": "Đơn Alipay không hợp lệ",
Loaded 100 of 102 files, more files were not shown because too many files have changed in this diff. Show more