Merge branch 'main' into rebuild/auth-identity-foundation

This commit is contained in:
IanShaw027 2026-04-22 00:35:34 +08:00
commit da1d26001f
67 changed files with 1550 additions and 613 deletions

59
.github/workflows/cla.yml vendored Normal file
View File

@ -0,0 +1,59 @@
name: "CLA Assistant"
on:
issue_comment:
types: [created]
pull_request_target:
types: [opened, reopened, closed, synchronize]
permissions:
actions: write
contents: write
pull-requests: write
statuses: write
jobs:
cla-check:
if: |
github.event_name == 'issue_comment' ||
(github.event_name == 'pull_request_target' && github.event.action != 'closed')
runs-on: ubuntu-latest
steps:
- name: "CLA Assistant"
if: |
(github.event.comment.body == 'recheck' ||
github.event.comment.body == 'I have read the CLA Document and I hereby sign the CLA') ||
github.event_name == 'pull_request_target'
uses: contributor-assistant/github-action@v2.6.1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
path-to-signatures: "cla.json"
path-to-document: "https://github.com/Wei-Shaw/sub2api/blob/main/CLA.md"
branch: "cla-signatures"
allowlist: "dependabot[bot],renovate[bot],bot*"
lock-pullrequest-aftermerge: false
custom-notsigned-prcomment: |
Thank you for your contribution! Before we can merge this PR, we need $you to sign our [Contributor License Agreement (CLA)](https://github.com/Wei-Shaw/sub2api/blob/main/CLA.md).
**To sign**, please reply with the following comment:
> I have read the CLA Document and I hereby sign the CLA
You only need to sign once — it will be valid for all your future contributions to this project.
custom-pr-sign-comment: "I have read the CLA Document and I hereby sign the CLA"
custom-allsigned-prcomment: "All contributors have signed the CLA. ✅"
cla-lock:
if: github.event_name == 'pull_request_target' && github.event.action == 'closed' && github.event.pull_request.merged == true
runs-on: ubuntu-latest
steps:
- name: "Lock merged PR"
uses: contributor-assistant/github-action@v2.6.1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
path-to-signatures: "cla.json"
path-to-document: "https://github.com/Wei-Shaw/sub2api/blob/main/CLA.md"
branch: "cla-signatures"
lock-pullrequest-aftermerge: true

73
CLA.md Normal file
View File

@ -0,0 +1,73 @@
# Sub2API Individual Contributor License Agreement (v1.0)
Thank you for your interest in contributing to Sub2API ("the Project"). This Contributor License Agreement ("Agreement") documents the rights granted by contributors to the Project.
By signing this Agreement, you accept and agree to the following terms and conditions for your present and future contributions submitted to the Project.
## 1. Definitions
- **"You" (or "Your")** means the copyright owner or legal entity authorized by the copyright owner that is making this Agreement.
- **"Contribution"** means any original work of authorship, including any modifications or additions to an existing work, that is intentionally submitted by You to the Project for inclusion in, or documentation of, any of the products owned or managed by the Project. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Project or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Project for the purpose of discussing and improving the Project, but excluding communication that is conspicuously marked or otherwise designated in writing by You as "Not a Contribution."
- **"Project Owner"** means Wesley Liddick, or any individual or legal entity to whom Wesley Liddick has explicitly assigned or transferred ownership of the Project in writing, and their respective successors and assigns.
## 2. Grant of Copyright License
Subject to the terms and conditions of this Agreement, You hereby grant to the Project Owner a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, sublicense, and distribute Your Contributions and such derivative works. This license includes, without limitation, the right to sublicense, assign, and transfer these rights to any third party, including without limitation any successor, assignee, or acquiring entity of the Project or the Project Owner, and to use Your Contributions under any license, including proprietary or commercial licenses.
## 3. Moral Rights
To the fullest extent permitted by applicable law, You irrevocably waive and agree not to assert any moral rights (including rights of attribution and integrity) that You may have in Your Contributions, and agree that the Project Owner and its licensees may use, modify, and distribute Your Contributions without attribution or other obligations arising from moral rights.
## 4. Grant of Patent License
Subject to the terms and conditions of this Agreement, You hereby grant to the Project Owner a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer Your Contributions, where such license applies only to those patent claims licensable by You that are necessarily infringed by Your Contribution(s) alone or by combination of Your Contribution(s) with the Project to which such Contribution(s) was submitted.
## 5. Representations and Warranties
You represent and warrant that:
(a) You are legally entitled to grant the above licenses.
(b) If Your employer(s) has rights to intellectual property that You create that includes Your Contributions, You have received permission to make Contributions on behalf of that employer, or that Your employer has waived such rights for Your Contributions to the Project.
(c) Each of Your Contributions is Your original creation, or You have sufficient rights to submit it under the terms of this Agreement. You agree to provide, upon request, reasonable documentation or explanation of any third-party materials included in Your Contributions.
## 6. No Warranty
Your Contributions are provided on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are not expected to provide support for Your Contributions, except to the extent You desire to provide support.
## 7. No Obligation
You understand that the decision to include Your Contribution in any product or project is entirely at the discretion of the Project Owner, and this Agreement does not obligate the Project Owner to use Your Contribution.
## 8. Retention of Rights
You retain ownership of the copyright in Your Contributions. This Agreement does not transfer any copyright or other intellectual property rights from You to the Project Owner. This Agreement only grants the licenses described above.
## 9. Term and Termination
This Agreement shall remain in effect indefinitely. You may terminate this Agreement prospectively by providing written notice to the Project Owner, but such termination shall not affect the licenses granted for Contributions submitted prior to the effective date of termination. The licenses granted herein for Contributions submitted prior to termination are perpetual and irrevocable.
## 10. Electronic Signature
You agree that Your electronic signature (including but not limited to typing a specific phrase in a pull request, issue, or other electronic communication) is legally binding and has the same force and effect as a handwritten signature. You consent to the use of electronic means to enter into this Agreement and acknowledge that this Agreement is enforceable as if executed in a traditional written format.
## 11. General Provisions
**Entire Agreement.** This Agreement constitutes the entire agreement between You and the Project Owner with respect to Your Contributions and supersedes all prior or contemporaneous understandings regarding such subject matter.
**Severability.** If any provision of this Agreement is held to be unenforceable or invalid, that provision will be enforced to the maximum extent possible and the remaining provisions will remain in full force and effect.
**No Waiver.** The failure of the Project Owner to enforce any provision of this Agreement shall not constitute a waiver of that provision or any other provision.
**Amendment.** This Agreement may only be modified by a written instrument signed by both parties. Modifications to this Agreement apply only to Contributions submitted after the modified Agreement is published and accepted by You. Prior Contributions remain governed by the version of the Agreement in effect at the time of submission.
**Notification.** Notices under this Agreement shall be sent to the Project Owner via a GitHub issue on the Project repository. Notices are effective upon receipt.
---
**By signing this CLA, you acknowledge that you have read and understood this Agreement and agree to be bound by its terms.**
To sign, reply in the pull request with:
> I have read the CLA Document and I hereby sign the CLA

178
LICENSE
View File

@ -1,21 +1,165 @@
MIT License GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (c) 2025 Wesley Liddick Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all This version of the GNU Lesser General Public License incorporates
copies or substantial portions of the Software. the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 0. Additional Definitions.
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE As used herein, "this License" refers to version 3 of the GNU Lesser
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER General Public License, and the "GNU GPL" refers to version 3 of the GNU
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, General Public License.
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. "The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

View File

@ -96,6 +96,11 @@ Sub2API is an AI API gateway platform designed to distribute and manage API quot
<td>Huge thanks to BmoPlus for sponsoring this project! BmoPlus is a highly reliable AI account provider built strictly for heavy AI users and developers. They offer rock-solid, ready-to-use accounts and official top-up services for ChatGPT Plus / ChatGPT Pro (Full Warranty) / Claude Pro / Super Grok / Gemini Pro. By registering and ordering through <a href="https://shop.bmoplus.com/?utm_source=github">BmoPlus - Premium AI Accounts & Top-ups</a>, users can unlock the mind-blowing rate of 10% of the official GPT subscription price (90% OFF)</td> <td>Huge thanks to BmoPlus for sponsoring this project! BmoPlus is a highly reliable AI account provider built strictly for heavy AI users and developers. They offer rock-solid, ready-to-use accounts and official top-up services for ChatGPT Plus / ChatGPT Pro (Full Warranty) / Claude Pro / Super Grok / Gemini Pro. By registering and ordering through <a href="https://shop.bmoplus.com/?utm_source=github">BmoPlus - Premium AI Accounts & Top-ups</a>, users can unlock the mind-blowing rate of 10% of the official GPT subscription price (90% OFF)</td>
</tr> </tr>
<tr>
<td width="180"><a href="https://bestproxy.com/?keyword=a2e8iuol"><img src="assets/partners/logos/bestproxy.png" alt="bestproxy" width="150"></a></td>
<td>Thanks to Bestproxy for sponsoring this project! <a href="https://bestproxy.com/?keyword=a2e8iuol">Bestproxy</a> provides high-purity residential IPs with dedicated one-IP-per-account support. By combining real home networks with fingerprint isolation, it enables link environment isolation and reduces the probability of association-based risk control.</td>
</tr>
</table> </table>
## Ecosystem ## Ecosystem
@ -618,7 +623,9 @@ sub2api/
## License ## License
MIT License This project is licensed under the [GNU Lesser General Public License v3.0](LICENSE) (or later).
Copyright (c) 2026 Wesley Liddick
--- ---

View File

@ -95,6 +95,11 @@ Sub2API 是一个 AI API 网关平台,用于分发和管理 AI 产品订阅的
<td>感谢 BmoPlus 赞助了本项目BmoPlus 是一家专为AI订阅重度用户打造的可靠 AI 账号代充服务商,提供稳定的 ChatGPT Plus / ChatGPT Pro(全程质保) / Claude Pro / Super Grok / Gemini Pro 的官方代充&成品账号。 通过<a href="https://shop.bmoplus.com/?utm_source=github">BmoPlus AI成品号专卖/代充</a>注册下单的用户可享GPT 官网订阅一折 的震撼价格!</td> <td>感谢 BmoPlus 赞助了本项目BmoPlus 是一家专为AI订阅重度用户打造的可靠 AI 账号代充服务商,提供稳定的 ChatGPT Plus / ChatGPT Pro(全程质保) / Claude Pro / Super Grok / Gemini Pro 的官方代充&成品账号。 通过<a href="https://shop.bmoplus.com/?utm_source=github">BmoPlus AI成品号专卖/代充</a>注册下单的用户可享GPT 官网订阅一折 的震撼价格!</td>
</tr> </tr>
<tr>
<td width="180"><a href="https://bestproxy.com/?keyword=a2e8iuol"><img src="assets/partners/logos/bestproxy.png" alt="bestproxy" width="150"></a></td>
<td>感谢 Bestproxy 赞助了本项目!<a href="https://bestproxy.com/?keyword=a2e8iuol">Bestproxy</a> 是一家提供高纯度住宅IP支持一号一IP独享结合真实家庭网络与指纹隔离可实现链路环境隔离降低关联风控概率。</td>
</tr>
</table> </table>
## 生态项目 ## 生态项目
@ -679,7 +684,9 @@ sub2api/
## 许可证 ## 许可证
MIT License 本项目基于 [GNU 宽通用公共许可证 v3.0](LICENSE)(或更高版本)授权。
Copyright (c) 2026 Wesley Liddick
--- ---

View File

@ -95,6 +95,11 @@ Sub2API は、AI 製品のサブスクリプションから API クォータを
<td>本プロジェクトにご支援いただいた BmoPlus に感謝いたしますBmoPlusは、AIサブスクリプションのヘビーユーザー向けに特化した信頼性の高いAIアカウントサービスプロバイダーであり、安定した ChatGPT Plus / ChatGPT Pro (完全保証) / Claude Pro / Super Grok / Gemini Pro の公式代行チャージおよび即納アカウントを提供しています。こちらの<a href="https://shop.bmoplus.com/?utm_source=github">BmoPlus AIアカウント専門店/代行チャージ</a>経由でご登録・ご注文いただいたユーザー様は、GPTを 公式サイト価格の約1割90% OFF という驚異的な価格でご利用いただけます!</td> <td>本プロジェクトにご支援いただいた BmoPlus に感謝いたしますBmoPlusは、AIサブスクリプションのヘビーユーザー向けに特化した信頼性の高いAIアカウントサービスプロバイダーであり、安定した ChatGPT Plus / ChatGPT Pro (完全保証) / Claude Pro / Super Grok / Gemini Pro の公式代行チャージおよび即納アカウントを提供しています。こちらの<a href="https://shop.bmoplus.com/?utm_source=github">BmoPlus AIアカウント専門店/代行チャージ</a>経由でご登録・ご注文いただいたユーザー様は、GPTを 公式サイト価格の約1割90% OFF という驚異的な価格でご利用いただけます!</td>
</tr> </tr>
<tr>
<td width="180"><a href="https://bestproxy.com/?keyword=a2e8iuol"><img src="assets/partners/logos/bestproxy.png" alt="bestproxy" width="150"></a></td>
<td>Bestproxy のご支援に感謝します!<a href="https://bestproxy.com/?keyword=a2e8iuol">Bestproxy</a> は高純度の住宅IPを提供し、1アカウント1IP専有をサポートしています。実際の家庭ネットワークとフィンガープリント分離を組み合わせることで、リンク環境の分離を実現し、関連付けによるリスク管理の確率を低減します。</td>
</tr>
</table> </table>
## エコシステム ## エコシステム
@ -617,7 +622,9 @@ sub2api/
## ライセンス ## ライセンス
MIT License 本プロジェクトは [GNU Lesser General Public License v3.0](LICENSE)(またはそれ以降のバージョン)の下でライセンスされています。
Copyright (c) 2026 Wesley Liddick
--- ---

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.5 KiB

View File

@ -52,6 +52,11 @@ const (
ConnectionPoolIsolationAccountProxy = "account_proxy" ConnectionPoolIsolationAccountProxy = "account_proxy"
) )
// DefaultUpstreamResponseReadMaxBytes 上游非流式响应体的默认读取上限。
// 128 MB 可容纳 2-3 张 4K PNGbase64 膨胀 33%,单张 4K PNG 最坏约 67MB base64
// 可通过 gateway.upstream_response_read_max_bytes 配置项覆盖。
const DefaultUpstreamResponseReadMaxBytes int64 = 128 * 1024 * 1024
type Config struct { type Config struct {
Server ServerConfig `mapstructure:"server"` Server ServerConfig `mapstructure:"server"`
Log LogConfig `mapstructure:"log"` Log LogConfig `mapstructure:"log"`
@ -1407,7 +1412,7 @@ func setDefaults() {
viper.SetDefault("gateway.antigravity_fallback_cooldown_minutes", 1) viper.SetDefault("gateway.antigravity_fallback_cooldown_minutes", 1)
viper.SetDefault("gateway.antigravity_extra_retries", 10) viper.SetDefault("gateway.antigravity_extra_retries", 10)
viper.SetDefault("gateway.max_body_size", int64(256*1024*1024)) viper.SetDefault("gateway.max_body_size", int64(256*1024*1024))
viper.SetDefault("gateway.upstream_response_read_max_bytes", int64(8*1024*1024)) viper.SetDefault("gateway.upstream_response_read_max_bytes", DefaultUpstreamResponseReadMaxBytes)
viper.SetDefault("gateway.proxy_probe_response_read_max_bytes", int64(1024*1024)) viper.SetDefault("gateway.proxy_probe_response_read_max_bytes", int64(1024*1024))
viper.SetDefault("gateway.gemini_debug_response_headers", false) viper.SetDefault("gateway.gemini_debug_response_headers", false)
viper.SetDefault("gateway.connection_pool_isolation", ConnectionPoolIsolationAccountProxy) viper.SetDefault("gateway.connection_pool_isolation", ConnectionPoolIsolationAccountProxy)

View File

@ -215,7 +215,10 @@ type CreateOrderRequest struct {
PaymentSource string `json:"payment_source"` PaymentSource string `json:"payment_source"`
OrderType string `json:"order_type"` OrderType string `json:"order_type"`
PlanID int64 `json:"plan_id"` PlanID int64 `json:"plan_id"`
IsMobile *bool `json:"is_mobile,omitempty"` // IsMobile lets the frontend declare its mobile status directly. When
// nil we fall back to User-Agent heuristics (which miss iPadOS / some
// embedded browsers that strip the "Mobile" keyword).
IsMobile *bool `json:"is_mobile,omitempty"`
} }
// CreateOrder creates a new payment order. // CreateOrder creates a new payment order.
@ -247,7 +250,6 @@ func (h *PaymentHandler) CreateOrder(c *gin.Context) {
if req.IsMobile != nil { if req.IsMobile != nil {
mobile = *req.IsMobile mobile = *req.IsMobile
} }
result, err := h.paymentService.CreateOrder(c.Request.Context(), service.CreateOrderRequest{ result, err := h.paymentService.CreateOrder(c.Request.Context(), service.CreateOrderRequest{
UserID: subject.UserID, UserID: subject.UserID,
Amount: req.Amount, Amount: req.Amount,

View File

@ -10,12 +10,20 @@ import (
"strings" "strings"
) )
// AES256KeySize is the required key length (in bytes) for AES-256-GCM.
const AES256KeySize = 32
// Encrypt encrypts plaintext using AES-256-GCM with the given 32-byte key. // Encrypt encrypts plaintext using AES-256-GCM with the given 32-byte key.
// The output format is "iv:authTag:ciphertext" where each component is base64-encoded, // The output format is "iv:authTag:ciphertext" where each component is base64-encoded,
// matching the Node.js crypto.ts format for cross-compatibility. // matching the Node.js crypto.ts format for cross-compatibility.
//
// Deprecated: payment provider configs are now stored as plaintext JSON.
// This function is kept only for seeding legacy ciphertext in tests and for
// the transitional Decrypt fallback. Scheduled for removal after all live
// deployments complete migration by re-saving their configs.
func Encrypt(plaintext string, key []byte) (string, error) { func Encrypt(plaintext string, key []byte) (string, error) {
if len(key) != 32 { if len(key) != AES256KeySize {
return "", fmt.Errorf("encryption key must be 32 bytes, got %d", len(key)) return "", fmt.Errorf("encryption key must be %d bytes, got %d", AES256KeySize, len(key))
} }
block, err := aes.NewCipher(key) block, err := aes.NewCipher(key)
@ -51,9 +59,14 @@ func Encrypt(plaintext string, key []byte) (string, error) {
// Decrypt decrypts a ciphertext string produced by Encrypt. // Decrypt decrypts a ciphertext string produced by Encrypt.
// The input format is "iv:authTag:ciphertext" where each component is base64-encoded. // The input format is "iv:authTag:ciphertext" where each component is base64-encoded.
//
// Deprecated: payment provider configs are now stored as plaintext JSON.
// This function remains only as a read-path fallback for pre-migration
// ciphertext records. Scheduled for removal once all deployments re-save
// their provider configs through the admin UI.
func Decrypt(ciphertext string, key []byte) (string, error) { func Decrypt(ciphertext string, key []byte) (string, error) {
if len(key) != 32 { if len(key) != AES256KeySize {
return "", fmt.Errorf("encryption key must be 32 bytes, got %d", len(key)) return "", fmt.Errorf("encryption key must be %d bytes, got %d", AES256KeySize, len(key))
} }
parts := strings.SplitN(ciphertext, ":", 3) parts := strings.SplitN(ciphertext, ":", 3)

View File

@ -297,6 +297,9 @@ func (lb *DefaultLoadBalancer) buildSelection(selected *dbent.PaymentProviderIns
if err != nil { if err != nil {
return nil, fmt.Errorf("decrypt instance %d config: %w", selected.ID, err) return nil, fmt.Errorf("decrypt instance %d config: %w", selected.ID, err)
} }
if config == nil {
config = map[string]string{}
}
if selected.PaymentMode != "" { if selected.PaymentMode != "" {
config["paymentMode"] = selected.PaymentMode config["paymentMode"] = selected.PaymentMode
@ -311,16 +314,36 @@ func (lb *DefaultLoadBalancer) buildSelection(selected *dbent.PaymentProviderIns
}, nil }, nil
} }
func (lb *DefaultLoadBalancer) decryptConfig(encrypted string) (map[string]string, error) { // decryptConfig parses a stored provider config.
plaintext, err := Decrypt(encrypted, lb.encryptionKey) // New records are plaintext JSON; legacy records are AES-256-GCM ciphertext.
if err != nil { // Unreadable values (legacy ciphertext without a valid key, or malformed data)
return nil, err // are treated as empty so the service keeps running while the admin re-enters
// the config via the UI.
//
// TODO(deprecated-legacy-ciphertext): The AES fallback branch below is a
// transitional compatibility shim for pre-plaintext records. Remove it (and
// the encryptionKey field + the Decrypt import) after a few releases once all
// live deployments have re-saved their provider configs through the UI.
func (lb *DefaultLoadBalancer) decryptConfig(stored string) (map[string]string, error) {
if stored == "" {
return nil, nil
} }
var config map[string]string var config map[string]string
if err := json.Unmarshal([]byte(plaintext), &config); err != nil { if err := json.Unmarshal([]byte(stored), &config); err == nil {
return nil, fmt.Errorf("unmarshal config: %w", err) return config, nil
} }
return config, nil // Deprecated: legacy AES-256-GCM ciphertext fallback — scheduled for removal.
if len(lb.encryptionKey) == AES256KeySize {
//nolint:staticcheck // SA1019: intentional legacy fallback, scheduled for removal
if plaintext, err := Decrypt(stored, lb.encryptionKey); err == nil {
if err := json.Unmarshal([]byte(plaintext), &config); err == nil {
return config, nil
}
}
}
slog.Warn("payment provider config unreadable, treating as empty for re-entry",
"stored_len", len(stored))
return nil, nil
} }
// GetInstanceDailyAmount returns the total completed order amount for an instance today. // GetInstanceDailyAmount returns the total completed order amount for an instance today.

View File

@ -474,6 +474,103 @@ func TestStartOfDay(t *testing.T) {
} }
} }
func TestDecryptConfig_PlaintextAndLegacyCompat(t *testing.T) {
t.Parallel()
key := make([]byte, AES256KeySize)
for i := range key {
key[i] = byte(i + 1)
}
wrongKey := make([]byte, AES256KeySize)
for i := range wrongKey {
wrongKey[i] = byte(0xFF - i)
}
plaintextJSON := `{"appId":"app-123","secret":"sec-xyz"}`
legacyEncrypted, err := Encrypt(plaintextJSON, key)
if err != nil {
t.Fatalf("seed Encrypt: %v", err)
}
tests := []struct {
name string
stored string
key []byte
want map[string]string
}{
{
name: "empty stored returns nil map",
stored: "",
key: key,
want: nil,
},
{
name: "plaintext JSON parses directly",
stored: plaintextJSON,
key: nil,
want: map[string]string{"appId": "app-123", "secret": "sec-xyz"},
},
{
name: "plaintext JSON works even with key present",
stored: plaintextJSON,
key: key,
want: map[string]string{"appId": "app-123", "secret": "sec-xyz"},
},
{
name: "legacy ciphertext with correct key decrypts",
stored: legacyEncrypted,
key: key,
want: map[string]string{"appId": "app-123", "secret": "sec-xyz"},
},
{
name: "legacy ciphertext with no key treated as empty",
stored: legacyEncrypted,
key: nil,
want: nil,
},
{
name: "legacy ciphertext with wrong key treated as empty",
stored: legacyEncrypted,
key: wrongKey,
want: nil,
},
{
name: "garbage data treated as empty",
stored: "not-json-and-not-ciphertext",
key: key,
want: nil,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
lb := NewDefaultLoadBalancer(nil, tt.key)
got, err := lb.decryptConfig(tt.stored)
if err != nil {
t.Fatalf("decryptConfig unexpected error: %v", err)
}
if !stringMapEqual(got, tt.want) {
t.Fatalf("decryptConfig = %v, want %v", got, tt.want)
}
})
}
}
// stringMapEqual compares two map[string]string values; nil and empty are equal.
func stringMapEqual(a, b map[string]string) bool {
if len(a) != len(b) {
return false
}
for k, v := range a {
if bv, ok := b[k]; !ok || bv != v {
return false
}
}
return true
}
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Helpers // Helpers
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------

View File

@ -15,8 +15,8 @@ import (
// Alipay product codes. // Alipay product codes.
const ( const (
alipayProductCodePagePay = "FAST_INSTANT_TRADE_PAY"
alipayProductCodeWapPay = "QUICK_WAP_WAY" alipayProductCodeWapPay = "QUICK_WAP_WAY"
alipayProductCodePagePay = "FAST_INSTANT_TRADE_PAY"
) )
// Alipay response constants. // Alipay response constants.
@ -102,8 +102,13 @@ func (a *Alipay) MerchantIdentityMetadata() map[string]string {
return map[string]string{"app_id": appID} return map[string]string{"app_id": appID}
} }
// CreatePayment creates an Alipay payment page URL. // CreatePayment creates an Alipay payment using redirect-only flow:
func (a *Alipay) CreatePayment(ctx context.Context, req payment.CreatePaymentRequest) (*payment.CreatePaymentResponse, error) { // - Mobile (H5): alipay.trade.wap.pay — returns a URL the browser jumps to.
// - PC: alipay.trade.page.pay — returns a gateway URL the browser opens in a
// new window; Alipay's own page then shows login/QR. We intentionally do
// NOT encode the URL into a QR on the client (it isn't a scannable payload
// and would produce an invalid scan result).
func (a *Alipay) CreatePayment(_ context.Context, req payment.CreatePaymentRequest) (*payment.CreatePaymentResponse, error) {
client, err := a.getClient() client, err := a.getClient()
if err != nil { if err != nil {
return nil, err return nil, err
@ -119,44 +124,46 @@ func (a *Alipay) CreatePayment(ctx context.Context, req payment.CreatePaymentReq
} }
if req.IsMobile { if req.IsMobile {
return a.createTrade(ctx, client, req, notifyURL, returnURL, true) return a.createWapTrade(client, req, notifyURL, returnURL)
} }
return a.createTrade(ctx, client, req, notifyURL, returnURL, false) return a.createPagePayTrade(client, req, notifyURL, returnURL)
} }
func (a *Alipay) createTrade(ctx context.Context, client *alipay.Client, req payment.CreatePaymentRequest, notifyURL, returnURL string, isMobile bool) (*payment.CreatePaymentResponse, error) { func (a *Alipay) createWapTrade(client *alipay.Client, req payment.CreatePaymentRequest, notifyURL, returnURL string) (*payment.CreatePaymentResponse, error) {
if isMobile { param := alipay.TradeWapPay{}
param := alipay.TradeWapPay{}
param.OutTradeNo = req.OrderID
param.TotalAmount = req.Amount
param.Subject = req.Subject
param.ProductCode = alipayProductCodeWapPay
param.NotifyURL = notifyURL
param.ReturnURL = returnURL
payURL, err := alipayTradeWapPay(client, param)
if err != nil {
return nil, fmt.Errorf("alipay TradeWapPay: %w", err)
}
return &payment.CreatePaymentResponse{
TradeNo: req.OrderID,
PayURL: payURL.String(),
}, nil
}
param := alipay.TradePreCreate{}
param.OutTradeNo = req.OrderID param.OutTradeNo = req.OrderID
param.TotalAmount = req.Amount param.TotalAmount = req.Amount
param.Subject = req.Subject param.Subject = req.Subject
param.ProductCode = alipayProductCodeWapPay
param.NotifyURL = notifyURL param.NotifyURL = notifyURL
param.ReturnURL = returnURL
resp, err := alipayTradePreCreate(ctx, client, param) payURL, err := client.TradeWapPay(param)
if err != nil { if err != nil {
return nil, fmt.Errorf("alipay TradePreCreate: %w", err) return nil, fmt.Errorf("alipay TradeWapPay: %w", err)
} }
return &payment.CreatePaymentResponse{ return &payment.CreatePaymentResponse{
TradeNo: req.OrderID, TradeNo: req.OrderID,
QRCode: strings.TrimSpace(resp.QRCode), PayURL: payURL.String(),
}, nil
}
func (a *Alipay) createPagePayTrade(client *alipay.Client, req payment.CreatePaymentRequest, notifyURL, returnURL string) (*payment.CreatePaymentResponse, error) {
param := alipay.TradePagePay{}
param.OutTradeNo = req.OrderID
param.TotalAmount = req.Amount
param.Subject = req.Subject
param.ProductCode = alipayProductCodePagePay
param.NotifyURL = notifyURL
param.ReturnURL = returnURL
payURL, err := alipayTradePagePay(client, param)
if err != nil {
return nil, fmt.Errorf("alipay TradePagePay: %w", err)
}
return &payment.CreatePaymentResponse{
TradeNo: req.OrderID,
PayURL: payURL.String(),
}, nil }, nil
} }

View File

@ -3,16 +3,17 @@ package provider
import ( import (
"bytes" "bytes"
"context" "context"
"crypto/rsa"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
"net/url" "net/url"
"strconv"
"strings" "strings"
"sync" "sync"
"time" "time"
"github.com/Wei-Shaw/sub2api/internal/payment" "github.com/Wei-Shaw/sub2api/internal/payment"
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
"github.com/wechatpay-apiv3/wechatpay-go/core" "github.com/wechatpay-apiv3/wechatpay-go/core"
"github.com/wechatpay-apiv3/wechatpay-go/core/auth/verifiers" "github.com/wechatpay-apiv3/wechatpay-go/core/auth/verifiers"
"github.com/wechatpay-apiv3/wechatpay-go/core/notify" "github.com/wechatpay-apiv3/wechatpay-go/core/notify"
@ -84,15 +85,35 @@ type Wxpay struct {
notifyHandler *notify.Handler notifyHandler *notify.Handler
} }
const wxpayAPIv3KeyLength = 32
func NewWxpay(instanceID string, config map[string]string) (*Wxpay, error) { func NewWxpay(instanceID string, config map[string]string) (*Wxpay, error) {
required := []string{"appId", "mchId", "privateKey", "apiV3Key", "publicKey", "publicKeyId", "certSerial"} // All fields are required. Platform-certificate mode is intentionally unsupported —
// WeChat has been migrating all merchants to the pubkey verifier since 2024-10,
// and newly-provisioned merchants cannot download platform certificates at all.
required := []string{"appId", "mchId", "privateKey", "apiV3Key", "certSerial", "publicKey", "publicKeyId"}
for _, k := range required { for _, k := range required {
if config[k] == "" { if config[k] == "" {
return nil, fmt.Errorf("wxpay config missing required key: %s", k) return nil, infraerrors.BadRequest("WXPAY_CONFIG_MISSING_KEY", "missing_required_key").
WithMetadata(map[string]string{"key": k})
} }
} }
if len(config["apiV3Key"]) != 32 { if len(config["apiV3Key"]) != wxpayAPIv3KeyLength {
return nil, fmt.Errorf("wxpay apiV3Key must be exactly 32 bytes, got %d", len(config["apiV3Key"])) return nil, infraerrors.BadRequest("WXPAY_CONFIG_INVALID_KEY_LENGTH", "invalid_key_length").
WithMetadata(map[string]string{
"key": "apiV3Key",
"expected": strconv.Itoa(wxpayAPIv3KeyLength),
"actual": strconv.Itoa(len(config["apiV3Key"])),
})
}
// Parse PEMs eagerly so malformed keys surface at save time, not at order creation.
if _, err := utils.LoadPrivateKey(formatPEM(config["privateKey"], "PRIVATE KEY")); err != nil {
return nil, infraerrors.BadRequest("WXPAY_CONFIG_INVALID_KEY", "invalid_key").
WithMetadata(map[string]string{"key": "privateKey"})
}
if _, err := utils.LoadPublicKey(formatPEM(config["publicKey"], "PUBLIC KEY")); err != nil {
return nil, infraerrors.BadRequest("WXPAY_CONFIG_INVALID_KEY", "invalid_key").
WithMetadata(map[string]string{"key": "publicKey"})
} }
return &Wxpay{instanceID: instanceID, config: config}, nil return &Wxpay{instanceID: instanceID, config: config}, nil
} }
@ -127,14 +148,19 @@ func (w *Wxpay) ensureClient() (*core.Client, error) {
if w.coreClient != nil { if w.coreClient != nil {
return w.coreClient, nil return w.coreClient, nil
} }
privateKey, publicKey, err := w.loadKeyPair() privateKey, err := utils.LoadPrivateKey(formatPEM(w.config["privateKey"], "PRIVATE KEY"))
if err != nil { if err != nil {
return nil, err return nil, infraerrors.BadRequest("WXPAY_CONFIG_INVALID_KEY", "invalid_key").
WithMetadata(map[string]string{"key": "privateKey"})
}
publicKey, err := utils.LoadPublicKey(formatPEM(w.config["publicKey"], "PUBLIC KEY"))
if err != nil {
return nil, infraerrors.BadRequest("WXPAY_CONFIG_INVALID_KEY", "invalid_key").
WithMetadata(map[string]string{"key": "publicKey"})
} }
certSerial := w.config["certSerial"]
verifier := verifiers.NewSHA256WithRSAPubkeyVerifier(w.config["publicKeyId"], *publicKey) verifier := verifiers.NewSHA256WithRSAPubkeyVerifier(w.config["publicKeyId"], *publicKey)
client, err := core.NewClient(context.Background(), client, err := core.NewClient(context.Background(),
option.WithMerchantCredential(w.config["mchId"], certSerial, privateKey), option.WithMerchantCredential(w.config["mchId"], w.config["certSerial"], privateKey),
option.WithVerifier(verifier)) option.WithVerifier(verifier))
if err != nil { if err != nil {
return nil, fmt.Errorf("wxpay init client: %w", err) return nil, fmt.Errorf("wxpay init client: %w", err)
@ -148,18 +174,6 @@ func (w *Wxpay) ensureClient() (*core.Client, error) {
return w.coreClient, nil return w.coreClient, nil
} }
func (w *Wxpay) loadKeyPair() (*rsa.PrivateKey, *rsa.PublicKey, error) {
privateKey, err := utils.LoadPrivateKey(formatPEM(w.config["privateKey"], "PRIVATE KEY"))
if err != nil {
return nil, nil, fmt.Errorf("wxpay load private key: %w", err)
}
publicKey, err := utils.LoadPublicKey(formatPEM(w.config["publicKey"], "PUBLIC KEY"))
if err != nil {
return nil, nil, fmt.Errorf("wxpay load public key: %w", err)
}
return privateKey, publicKey, nil
}
func (w *Wxpay) CreatePayment(ctx context.Context, req payment.CreatePaymentRequest) (*payment.CreatePaymentResponse, error) { func (w *Wxpay) CreatePayment(ctx context.Context, req payment.CreatePaymentRequest) (*payment.CreatePaymentResponse, error) {
client, err := w.ensureClient() client, err := w.ensureClient()
if err != nil { if err != nil {

View File

@ -4,6 +4,10 @@ package provider
import ( import (
"context" "context"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"net/url" "net/url"
"strings" "strings"
"testing" "testing"
@ -16,6 +20,26 @@ import (
"github.com/wechatpay-apiv3/wechatpay-go/services/payments/native" "github.com/wechatpay-apiv3/wechatpay-go/services/payments/native"
) )
// generateTestKeyPair returns a fresh RSA 2048 key pair as PEM strings.
// The wechatpay-go SDK expects PKCS8 private keys and PKIX public keys.
func generateTestKeyPair(t *testing.T) (privPEM, pubPEM string) {
t.Helper()
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatalf("generate rsa key: %v", err)
}
privDER, err := x509.MarshalPKCS8PrivateKey(key)
if err != nil {
t.Fatalf("marshal pkcs8: %v", err)
}
pubDER, err := x509.MarshalPKIXPublicKey(&key.PublicKey)
if err != nil {
t.Fatalf("marshal pkix: %v", err)
}
return string(pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: privDER})),
string(pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: pubDER}))
}
func TestMapWxState(t *testing.T) { func TestMapWxState(t *testing.T) {
t.Parallel() t.Parallel()
@ -183,13 +207,14 @@ func TestFormatPEM(t *testing.T) {
func TestNewWxpay(t *testing.T) { func TestNewWxpay(t *testing.T) {
t.Parallel() t.Parallel()
privPEM, pubPEM := generateTestKeyPair(t)
validConfig := map[string]string{ validConfig := map[string]string{
"appId": "wx1234567890", "appId": "wx1234567890",
"mchId": "1234567890", "mchId": "1234567890",
"privateKey": "fake-private-key", "privateKey": privPEM,
"apiV3Key": "12345678901234567890123456789012", // exactly 32 bytes "apiV3Key": "12345678901234567890123456789012", // exactly 32 bytes
"publicKey": "fake-public-key", "publicKey": pubPEM,
"publicKeyId": "key-id-001", "publicKeyId": "PUB_KEY_ID_TEST",
"certSerial": "SERIAL001", "certSerial": "SERIAL001",
} }
@ -240,6 +265,12 @@ func TestNewWxpay(t *testing.T) {
wantErr: true, wantErr: true,
errSubstr: "apiV3Key", errSubstr: "apiV3Key",
}, },
{
name: "missing certSerial",
config: withOverride(map[string]string{"certSerial": ""}),
wantErr: true,
errSubstr: "certSerial",
},
{ {
name: "missing publicKey", name: "missing publicKey",
config: withOverride(map[string]string{"publicKey": ""}), config: withOverride(map[string]string{"publicKey": ""}),
@ -252,17 +283,29 @@ func TestNewWxpay(t *testing.T) {
wantErr: true, wantErr: true,
errSubstr: "publicKeyId", errSubstr: "publicKeyId",
}, },
{
name: "malformed privateKey PEM",
config: withOverride(map[string]string{"privateKey": "not-a-valid-pem"}),
wantErr: true,
errSubstr: "WXPAY_CONFIG_INVALID_KEY",
},
{
name: "malformed publicKey PEM",
config: withOverride(map[string]string{"publicKey": "not-a-valid-pem"}),
wantErr: true,
errSubstr: "WXPAY_CONFIG_INVALID_KEY",
},
{ {
name: "apiV3Key too short", name: "apiV3Key too short",
config: withOverride(map[string]string{"apiV3Key": "short"}), config: withOverride(map[string]string{"apiV3Key": "short"}),
wantErr: true, wantErr: true,
errSubstr: "exactly 32 bytes", errSubstr: "WXPAY_CONFIG_INVALID_KEY_LENGTH",
}, },
{ {
name: "apiV3Key too long", name: "apiV3Key too long",
config: withOverride(map[string]string{"apiV3Key": "123456789012345678901234567890123"}), // 33 bytes config: withOverride(map[string]string{"apiV3Key": "123456789012345678901234567890123"}), // 33 bytes
wantErr: true, wantErr: true,
errSubstr: "exactly 32 bytes", errSubstr: "WXPAY_CONFIG_INVALID_KEY_LENGTH",
}, },
} }

View File

@ -17,16 +17,9 @@ type Model struct {
var DefaultModels = []Model{ var DefaultModels = []Model{
{ID: "gpt-5.4", Object: "model", Created: 1738368000, OwnedBy: "openai", Type: "model", DisplayName: "GPT-5.4"}, {ID: "gpt-5.4", Object: "model", Created: 1738368000, OwnedBy: "openai", Type: "model", DisplayName: "GPT-5.4"},
{ID: "gpt-5.4-mini", Object: "model", Created: 1738368000, OwnedBy: "openai", Type: "model", DisplayName: "GPT-5.4 Mini"}, {ID: "gpt-5.4-mini", Object: "model", Created: 1738368000, OwnedBy: "openai", Type: "model", DisplayName: "GPT-5.4 Mini"},
{ID: "gpt-5.4-nano", Object: "model", Created: 1738368000, OwnedBy: "openai", Type: "model", DisplayName: "GPT-5.4 Nano"},
{ID: "gpt-5.3-codex", Object: "model", Created: 1735689600, OwnedBy: "openai", Type: "model", DisplayName: "GPT-5.3 Codex"}, {ID: "gpt-5.3-codex", Object: "model", Created: 1735689600, OwnedBy: "openai", Type: "model", DisplayName: "GPT-5.3 Codex"},
{ID: "gpt-5.3-codex-spark", Object: "model", Created: 1735689600, OwnedBy: "openai", Type: "model", DisplayName: "GPT-5.3 Codex Spark"}, {ID: "gpt-5.3-codex-spark", Object: "model", Created: 1735689600, OwnedBy: "openai", Type: "model", DisplayName: "GPT-5.3 Codex Spark"},
{ID: "gpt-5.2", Object: "model", Created: 1733875200, OwnedBy: "openai", Type: "model", DisplayName: "GPT-5.2"}, {ID: "gpt-5.2", Object: "model", Created: 1733875200, OwnedBy: "openai", Type: "model", DisplayName: "GPT-5.2"},
{ID: "gpt-5.2-codex", Object: "model", Created: 1733011200, OwnedBy: "openai", Type: "model", DisplayName: "GPT-5.2 Codex"},
{ID: "gpt-5.1-codex-max", Object: "model", Created: 1730419200, OwnedBy: "openai", Type: "model", DisplayName: "GPT-5.1 Codex Max"},
{ID: "gpt-5.1-codex", Object: "model", Created: 1730419200, OwnedBy: "openai", Type: "model", DisplayName: "GPT-5.1 Codex"},
{ID: "gpt-5.1", Object: "model", Created: 1731456000, OwnedBy: "openai", Type: "model", DisplayName: "GPT-5.1"},
{ID: "gpt-5.1-codex-mini", Object: "model", Created: 1730419200, OwnedBy: "openai", Type: "model", DisplayName: "GPT-5.1 Codex Mini"},
{ID: "gpt-5", Object: "model", Created: 1722988800, OwnedBy: "openai", Type: "model", DisplayName: "GPT-5"},
} }
// DefaultModelIDs returns the default model ID list // DefaultModelIDs returns the default model ID list
@ -39,7 +32,7 @@ func DefaultModelIDs() []string {
} }
// DefaultTestModel default model for testing OpenAI accounts // DefaultTestModel default model for testing OpenAI accounts
const DefaultTestModel = "gpt-5.1-codex" const DefaultTestModel = "gpt-5.4"
// DefaultInstructions default instructions for non-Codex CLI requests // DefaultInstructions default instructions for non-Codex CLI requests
// Content loaded from instructions.txt at compile time // Content loaded from instructions.txt at compile time

View File

@ -438,6 +438,9 @@ func (r *accountRepository) Delete(ctx context.Context, id int64) error {
if _, err := txClient.AccountGroup.Delete().Where(dbaccountgroup.AccountIDEQ(id)).Exec(ctx); err != nil { if _, err := txClient.AccountGroup.Delete().Where(dbaccountgroup.AccountIDEQ(id)).Exec(ctx); err != nil {
return err return err
} }
if _, err := txClient.ExecContext(ctx, "DELETE FROM scheduled_test_plans WHERE account_id = $1", id); err != nil {
return err
}
if _, err := txClient.Account.Delete().Where(dbaccount.IDEQ(id)).Exec(ctx); err != nil { if _, err := txClient.Account.Delete().Where(dbaccount.IDEQ(id)).Exec(ctx); err != nil {
return err return err
} }

View File

@ -121,6 +121,9 @@ func (a *Account) IsSchedulable() bool {
if a.TempUnschedulableUntil != nil && now.Before(*a.TempUnschedulableUntil) { if a.TempUnschedulableUntil != nil && now.Before(*a.TempUnschedulableUntil) {
return false return false
} }
if a.IsAPIKeyOrBedrock() && a.IsQuotaExceeded() {
return false
}
return true return true
} }

View File

@ -0,0 +1,123 @@
//go:build unit
package service
import (
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestAccountIsSchedulable_QuotaExceeded(t *testing.T) {
now := time.Now()
tests := []struct {
name string
account *Account
want bool
}{
{
name: "apikey daily quota exceeded",
account: &Account{
Status: StatusActive,
Schedulable: true,
Type: AccountTypeAPIKey,
Extra: map[string]any{
"quota_daily_limit": 10.0,
"quota_daily_used": 10.0,
"quota_daily_start": now.Add(-1 * time.Hour).Format(time.RFC3339),
},
},
want: false,
},
{
name: "apikey weekly quota exceeded",
account: &Account{
Status: StatusActive,
Schedulable: true,
Type: AccountTypeAPIKey,
Extra: map[string]any{
"quota_weekly_limit": 50.0,
"quota_weekly_used": 50.0,
"quota_weekly_start": now.Add(-2 * 24 * time.Hour).Format(time.RFC3339),
},
},
want: false,
},
{
name: "apikey total quota exceeded",
account: &Account{
Status: StatusActive,
Schedulable: true,
Type: AccountTypeAPIKey,
Extra: map[string]any{
"quota_limit": 100.0,
"quota_used": 100.0,
},
},
want: false,
},
{
name: "apikey quota not exceeded",
account: &Account{
Status: StatusActive,
Schedulable: true,
Type: AccountTypeAPIKey,
Extra: map[string]any{
"quota_daily_limit": 10.0,
"quota_daily_used": 5.0,
"quota_daily_start": now.Add(-1 * time.Hour).Format(time.RFC3339),
},
},
want: true,
},
{
name: "apikey expired daily period restores schedulable",
account: &Account{
Status: StatusActive,
Schedulable: true,
Type: AccountTypeAPIKey,
Extra: map[string]any{
"quota_daily_limit": 10.0,
"quota_daily_used": 10.0,
"quota_daily_start": now.Add(-25 * time.Hour).Format(time.RFC3339),
},
},
want: true,
},
{
name: "oauth ignores quota exceeded",
account: &Account{
Status: StatusActive,
Schedulable: true,
Type: AccountTypeOAuth,
Extra: map[string]any{
"quota_daily_limit": 10.0,
"quota_daily_used": 10.0,
"quota_daily_start": now.Add(-1 * time.Hour).Format(time.RFC3339),
},
},
want: true,
},
{
name: "bedrock quota exceeded",
account: &Account{
Status: StatusActive,
Schedulable: true,
Type: AccountTypeBedrock,
Extra: map[string]any{
"quota_limit": 200.0,
"quota_used": 200.0,
},
},
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
require.Equal(t, tt.want, tt.account.IsSchedulable())
})
}
}

View File

@ -651,6 +651,15 @@ func (s *adminServiceImpl) assignDefaultSubscriptions(ctx context.Context, userI
} }
func (s *adminServiceImpl) UpdateUser(ctx context.Context, id int64, input *UpdateUserInput) (*User, error) { func (s *adminServiceImpl) UpdateUser(ctx context.Context, id int64, input *UpdateUserInput) (*User, error) {
// 校验用户专属分组倍率:必须 > 0nil 合法,表示清除专属倍率)
if input.GroupRates != nil {
for groupID, rate := range input.GroupRates {
if rate != nil && *rate <= 0 {
return nil, fmt.Errorf("rate_multiplier must be > 0 (group_id=%d)", groupID)
}
}
}
user, err := s.userRepo.GetByID(ctx, id) user, err := s.userRepo.GetByID(ctx, id)
if err != nil { if err != nil {
return nil, err return nil, err
@ -1108,6 +1117,10 @@ func (s *adminServiceImpl) GetGroup(ctx context.Context, id int64) (*Group, erro
} }
func (s *adminServiceImpl) CreateGroup(ctx context.Context, input *CreateGroupInput) (*Group, error) { func (s *adminServiceImpl) CreateGroup(ctx context.Context, input *CreateGroupInput) (*Group, error) {
if input.RateMultiplier <= 0 {
return nil, errors.New("rate_multiplier must be > 0")
}
platform := input.Platform platform := input.Platform
if platform == "" { if platform == "" {
platform = PlatformAnthropic platform = PlatformAnthropic
@ -1347,6 +1360,9 @@ func (s *adminServiceImpl) UpdateGroup(ctx context.Context, id int64, input *Upd
group.Platform = input.Platform group.Platform = input.Platform
} }
if input.RateMultiplier != nil { if input.RateMultiplier != nil {
if *input.RateMultiplier <= 0 {
return nil, errors.New("rate_multiplier must be > 0")
}
group.RateMultiplier = *input.RateMultiplier group.RateMultiplier = *input.RateMultiplier
} }
if input.IsExclusive != nil { if input.IsExclusive != nil {
@ -1583,6 +1599,11 @@ func (s *adminServiceImpl) BatchSetGroupRateMultipliers(ctx context.Context, gro
if s.userGroupRateRepo == nil { if s.userGroupRateRepo == nil {
return nil return nil
} }
for _, e := range entries {
if e.RateMultiplier <= 0 {
return fmt.Errorf("rate_multiplier must be > 0 (user_id=%d)", e.UserID)
}
}
return s.userGroupRateRepo.SyncGroupRateMultipliers(ctx, groupID, entries) return s.userGroupRateRepo.SyncGroupRateMultipliers(ctx, groupID, entries)
} }

View File

@ -621,6 +621,7 @@ func TestAdminService_CreateGroup_InvalidRequestFallbackRejectsUnsupportedPlatfo
_, err := svc.CreateGroup(context.Background(), &CreateGroupInput{ _, err := svc.CreateGroup(context.Background(), &CreateGroupInput{
Name: "g1", Name: "g1",
Platform: PlatformOpenAI, Platform: PlatformOpenAI,
RateMultiplier: 1.0,
SubscriptionType: SubscriptionTypeStandard, SubscriptionType: SubscriptionTypeStandard,
FallbackGroupIDOnInvalidRequest: &fallbackID, FallbackGroupIDOnInvalidRequest: &fallbackID,
}) })
@ -641,6 +642,7 @@ func TestAdminService_CreateGroup_InvalidRequestFallbackRejectsSubscription(t *t
_, err := svc.CreateGroup(context.Background(), &CreateGroupInput{ _, err := svc.CreateGroup(context.Background(), &CreateGroupInput{
Name: "g1", Name: "g1",
Platform: PlatformAnthropic, Platform: PlatformAnthropic,
RateMultiplier: 1.0,
SubscriptionType: SubscriptionTypeSubscription, SubscriptionType: SubscriptionTypeSubscription,
FallbackGroupIDOnInvalidRequest: &fallbackID, FallbackGroupIDOnInvalidRequest: &fallbackID,
}) })
@ -695,6 +697,7 @@ func TestAdminService_CreateGroup_InvalidRequestFallbackRejectsFallbackGroup(t *
_, err := svc.CreateGroup(context.Background(), &CreateGroupInput{ _, err := svc.CreateGroup(context.Background(), &CreateGroupInput{
Name: "g1", Name: "g1",
Platform: PlatformAnthropic, Platform: PlatformAnthropic,
RateMultiplier: 1.0,
SubscriptionType: SubscriptionTypeStandard, SubscriptionType: SubscriptionTypeStandard,
FallbackGroupIDOnInvalidRequest: &fallbackID, FallbackGroupIDOnInvalidRequest: &fallbackID,
}) })
@ -713,6 +716,7 @@ func TestAdminService_CreateGroup_InvalidRequestFallbackNotFound(t *testing.T) {
_, err := svc.CreateGroup(context.Background(), &CreateGroupInput{ _, err := svc.CreateGroup(context.Background(), &CreateGroupInput{
Name: "g1", Name: "g1",
Platform: PlatformAnthropic, Platform: PlatformAnthropic,
RateMultiplier: 1.0,
SubscriptionType: SubscriptionTypeStandard, SubscriptionType: SubscriptionTypeStandard,
FallbackGroupIDOnInvalidRequest: &fallbackID, FallbackGroupIDOnInvalidRequest: &fallbackID,
}) })
@ -733,6 +737,7 @@ func TestAdminService_CreateGroup_InvalidRequestFallbackAllowsAntigravity(t *tes
group, err := svc.CreateGroup(context.Background(), &CreateGroupInput{ group, err := svc.CreateGroup(context.Background(), &CreateGroupInput{
Name: "g1", Name: "g1",
Platform: PlatformAntigravity, Platform: PlatformAntigravity,
RateMultiplier: 1.0,
SubscriptionType: SubscriptionTypeStandard, SubscriptionType: SubscriptionTypeStandard,
FallbackGroupIDOnInvalidRequest: &fallbackID, FallbackGroupIDOnInvalidRequest: &fallbackID,
}) })
@ -750,6 +755,7 @@ func TestAdminService_CreateGroup_InvalidRequestFallbackClearsOnZero(t *testing.
group, err := svc.CreateGroup(context.Background(), &CreateGroupInput{ group, err := svc.CreateGroup(context.Background(), &CreateGroupInput{
Name: "g1", Name: "g1",
Platform: PlatformAnthropic, Platform: PlatformAnthropic,
RateMultiplier: 1.0,
SubscriptionType: SubscriptionTypeStandard, SubscriptionType: SubscriptionTypeStandard,
FallbackGroupIDOnInvalidRequest: &zero, FallbackGroupIDOnInvalidRequest: &zero,
}) })

View File

@ -203,17 +203,6 @@ func (s *BillingService) initFallbackPricing() {
SupportsCacheBreakdown: false, SupportsCacheBreakdown: false,
} }
// OpenAI GPT-5.1(本地兜底,防止动态定价不可用时拒绝计费)
s.fallbackPrices["gpt-5.1"] = &ModelPricing{
InputPricePerToken: 1.25e-6, // $1.25 per MTok
InputPricePerTokenPriority: 2.5e-6, // $2.5 per MTok
OutputPricePerToken: 10e-6, // $10 per MTok
OutputPricePerTokenPriority: 20e-6, // $20 per MTok
CacheCreationPricePerToken: 1.25e-6, // $1.25 per MTok
CacheReadPricePerToken: 0.125e-6,
CacheReadPricePerTokenPriority: 0.25e-6,
SupportsCacheBreakdown: false,
}
// OpenAI GPT-5.4(业务指定价格) // OpenAI GPT-5.4(业务指定价格)
s.fallbackPrices["gpt-5.4"] = &ModelPricing{ s.fallbackPrices["gpt-5.4"] = &ModelPricing{
InputPricePerToken: 2.5e-6, // $2.5 per MTok InputPricePerToken: 2.5e-6, // $2.5 per MTok
@ -234,12 +223,6 @@ func (s *BillingService) initFallbackPricing() {
CacheReadPricePerToken: 7.5e-8, CacheReadPricePerToken: 7.5e-8,
SupportsCacheBreakdown: false, SupportsCacheBreakdown: false,
} }
s.fallbackPrices["gpt-5.4-nano"] = &ModelPricing{
InputPricePerToken: 2e-7,
OutputPricePerToken: 1.25e-6,
CacheReadPricePerToken: 2e-8,
SupportsCacheBreakdown: false,
}
// OpenAI GPT-5.2(本地兜底) // OpenAI GPT-5.2(本地兜底)
s.fallbackPrices["gpt-5.2"] = &ModelPricing{ s.fallbackPrices["gpt-5.2"] = &ModelPricing{
InputPricePerToken: 1.75e-6, InputPricePerToken: 1.75e-6,
@ -251,8 +234,8 @@ func (s *BillingService) initFallbackPricing() {
CacheReadPricePerTokenPriority: 0.35e-6, CacheReadPricePerTokenPriority: 0.35e-6,
SupportsCacheBreakdown: false, SupportsCacheBreakdown: false,
} }
// Codex 族兜底统一按 GPT-5.1 Codex 价格计费 // Codex 族兜底统一按 GPT-5.3 Codex 价格计费
s.fallbackPrices["gpt-5.1-codex"] = &ModelPricing{ s.fallbackPrices["gpt-5.3-codex"] = &ModelPricing{
InputPricePerToken: 1.5e-6, // $1.5 per MTok InputPricePerToken: 1.5e-6, // $1.5 per MTok
InputPricePerTokenPriority: 3e-6, // $3 per MTok InputPricePerTokenPriority: 3e-6, // $3 per MTok
OutputPricePerToken: 12e-6, // $12 per MTok OutputPricePerToken: 12e-6, // $12 per MTok
@ -262,17 +245,6 @@ func (s *BillingService) initFallbackPricing() {
CacheReadPricePerTokenPriority: 0.3e-6, CacheReadPricePerTokenPriority: 0.3e-6,
SupportsCacheBreakdown: false, SupportsCacheBreakdown: false,
} }
s.fallbackPrices["gpt-5.2-codex"] = &ModelPricing{
InputPricePerToken: 1.75e-6,
InputPricePerTokenPriority: 3.5e-6,
OutputPricePerToken: 14e-6,
OutputPricePerTokenPriority: 28e-6,
CacheCreationPricePerToken: 1.75e-6,
CacheReadPricePerToken: 0.175e-6,
CacheReadPricePerTokenPriority: 0.35e-6,
SupportsCacheBreakdown: false,
}
s.fallbackPrices["gpt-5.3-codex"] = s.fallbackPrices["gpt-5.1-codex"]
} }
// getFallbackPricing 根据模型系列获取回退价格 // getFallbackPricing 根据模型系列获取回退价格
@ -318,20 +290,12 @@ func (s *BillingService) getFallbackPricing(model string) *ModelPricing {
switch normalized { switch normalized {
case "gpt-5.4-mini": case "gpt-5.4-mini":
return s.fallbackPrices["gpt-5.4-mini"] return s.fallbackPrices["gpt-5.4-mini"]
case "gpt-5.4-nano":
return s.fallbackPrices["gpt-5.4-nano"]
case "gpt-5.4": case "gpt-5.4":
return s.fallbackPrices["gpt-5.4"] return s.fallbackPrices["gpt-5.4"]
case "gpt-5.2": case "gpt-5.2":
return s.fallbackPrices["gpt-5.2"] return s.fallbackPrices["gpt-5.2"]
case "gpt-5.2-codex": case "gpt-5.3-codex", "gpt-5.3-codex-spark":
return s.fallbackPrices["gpt-5.2-codex"]
case "gpt-5.3-codex":
return s.fallbackPrices["gpt-5.3-codex"] return s.fallbackPrices["gpt-5.3-codex"]
case "gpt-5.1-codex", "gpt-5.1-codex-max", "gpt-5.1-codex-mini", "codex-mini-latest":
return s.fallbackPrices["gpt-5.1-codex"]
case "gpt-5.1":
return s.fallbackPrices["gpt-5.1"]
} }
} }
@ -448,8 +412,9 @@ func (s *BillingService) CalculateCostUnified(input CostInput) (*CostBreakdown,
}) })
} }
if input.RateMultiplier <= 0 { // 保存时强制 > 0若仍有负数泄漏缓存/迁移残留),按 0 处理避免按 1x 误扣。
input.RateMultiplier = 1.0 if input.RateMultiplier < 0 {
input.RateMultiplier = 0
} }
var breakdown *CostBreakdown var breakdown *CostBreakdown
@ -493,8 +458,9 @@ func (s *BillingService) computeTokenBreakdown(
rateMultiplier float64, serviceTier string, rateMultiplier float64, serviceTier string,
applyLongCtx bool, applyLongCtx bool,
) *CostBreakdown { ) *CostBreakdown {
if rateMultiplier <= 0 { // 保存时强制 > 0若仍有负数泄漏按 0 处理避免按 1x 误扣。
rateMultiplier = 1.0 if rateMultiplier < 0 {
rateMultiplier = 0
} }
inputPrice := pricing.InputPricePerToken inputPrice := pricing.InputPricePerToken
@ -665,8 +631,13 @@ func (s *BillingService) shouldApplySessionLongContextPricing(tokens UsageTokens
} }
func isOpenAIGPT54Model(model string) bool { func isOpenAIGPT54Model(model string) bool {
normalized := normalizeCodexModel(strings.TrimSpace(strings.ToLower(model))) trimmed := strings.TrimSpace(strings.ToLower(model))
return normalized == "gpt-5.4" // 仅当模型字符串实际属于 GPT-5/Codex 族时才做归一判定,避免 normalizeCodexModel
// 的默认兜底把非 OpenAI 模型claude-*、gemini-*、gpt-4o误识别为 gpt-5.4。
if !strings.Contains(trimmed, "gpt-5") && !strings.Contains(trimmed, "codex") {
return false
}
return normalizeCodexModel(trimmed) == "gpt-5.4"
} }
// CalculateCostWithConfig 使用配置中的默认倍率计算费用 // CalculateCostWithConfig 使用配置中的默认倍率计算费用
@ -831,9 +802,9 @@ func (s *BillingService) CalculateImageCost(model string, imageSize string, imag
// 计算总费用 // 计算总费用
totalCost := unitPrice * float64(imageCount) totalCost := unitPrice * float64(imageCount)
// 应用倍率 // 应用倍率(保存时强制 > 0负数按 0 处理避免按 1x 误扣)
if rateMultiplier <= 0 { if rateMultiplier < 0 {
rateMultiplier = 1.0 rateMultiplier = 0
} }
actualCost := totalCost * rateMultiplier actualCost := totalCost * rateMultiplier

View File

@ -90,13 +90,14 @@ func TestCalculateImageCost_NegativeCount(t *testing.T) {
require.Equal(t, 0.0, cost.ActualCost) require.Equal(t, 0.0, cost.ActualCost)
} }
// TestCalculateImageCost_ZeroRateMultiplier 测试费率倍数为 0 时默认使用 1.0 // TestCalculateImageCost_ZeroRateMultiplier 锁定新行为:倍率 0 直接按 0 计费
// (保存时已强制 > 0若仍有 0 泄漏到计费层,零消耗比历史的 1.0 更安全)。
func TestCalculateImageCost_ZeroRateMultiplier(t *testing.T) { func TestCalculateImageCost_ZeroRateMultiplier(t *testing.T) {
svc := &BillingService{} svc := &BillingService{}
cost := svc.CalculateImageCost("gemini-3-pro-image", "2K", 1, nil, 0) cost := svc.CalculateImageCost("gemini-3-pro-image", "2K", 1, nil, 0)
require.InDelta(t, 0.201, cost.TotalCost, 0.0001) require.InDelta(t, 0.201, cost.TotalCost, 0.0001)
require.InDelta(t, 0.201, cost.ActualCost, 0.0001) // 0 倍率当作 1.0 处理 require.InDelta(t, 0.0, cost.ActualCost, 1e-10)
} }
// TestGetImageUnitPrice_GroupPriorityOverDefault 测试分组价格优先于默认价格 // TestGetImageUnitPrice_GroupPriorityOverDefault 测试分组价格优先于默认价格

View File

@ -0,0 +1,63 @@
//go:build unit
package service
import (
"testing"
"github.com/stretchr/testify/require"
)
// TestCalculateCost_RateMultiplier_NegativeClampedToZero 锁定负数倍率被
// 钳制为 0而非历史上的 1.0),避免配置异常导致静默按标准价扣费。
func TestCalculateCost_RateMultiplier_NegativeClampedToZero(t *testing.T) {
svc := newTestBillingService()
tokens := UsageTokens{InputTokens: 1000, OutputTokens: 500}
tests := []struct {
name string
multiplier float64
wantRatio float64 // ActualCost / TotalCost
}{
{"negative clamped to 0", -1.5, 0},
{"zero passes through as 0 (defense in depth)", 0, 0},
{"positive 2x applied", 2.0, 2.0},
{"positive 0.5x applied", 0.5, 0.5},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cost, err := svc.CalculateCost("claude-sonnet-4", tokens, tt.multiplier)
require.NoError(t, err)
require.Greater(t, cost.TotalCost, 0.0, "TotalCost should be non-zero")
require.InDelta(t, tt.wantRatio*cost.TotalCost, cost.ActualCost, 1e-9)
})
}
}
// TestCalculateImageCost_RateMultiplier_NegativeClampedToZero 图片按次计费路径
// 同样遵循"负数 → 0"语义。
func TestCalculateImageCost_RateMultiplier_NegativeClampedToZero(t *testing.T) {
svc := newTestBillingService()
price := 0.04
cfg := &ImagePriceConfig{Price1K: &price}
tests := []struct {
name string
multiplier float64
wantRatio float64
}{
{"negative clamped to 0", -0.5, 0},
{"zero passes through", 0, 0},
{"positive 3x applied", 3.0, 3.0},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cost := svc.CalculateImageCost("imagen-3", "1K", 2, cfg, tt.multiplier)
require.NotNil(t, cost)
require.Greater(t, cost.TotalCost, 0.0)
require.InDelta(t, tt.wantRatio*cost.TotalCost, cost.ActualCost, 1e-9)
})
}
}

View File

@ -71,34 +71,6 @@ func TestCalculateCost_RateMultiplier(t *testing.T) {
require.InDelta(t, cost1x.ActualCost*2, cost2x.ActualCost, 1e-10) require.InDelta(t, cost1x.ActualCost*2, cost2x.ActualCost, 1e-10)
} }
func TestCalculateCost_ZeroMultiplierDefaultsToOne(t *testing.T) {
svc := newTestBillingService()
tokens := UsageTokens{InputTokens: 1000}
costZero, err := svc.CalculateCost("claude-sonnet-4", tokens, 0)
require.NoError(t, err)
costOne, err := svc.CalculateCost("claude-sonnet-4", tokens, 1.0)
require.NoError(t, err)
require.InDelta(t, costOne.ActualCost, costZero.ActualCost, 1e-10)
}
func TestCalculateCost_NegativeMultiplierDefaultsToOne(t *testing.T) {
svc := newTestBillingService()
tokens := UsageTokens{InputTokens: 1000}
costNeg, err := svc.CalculateCost("claude-sonnet-4", tokens, -1.0)
require.NoError(t, err)
costOne, err := svc.CalculateCost("claude-sonnet-4", tokens, 1.0)
require.NoError(t, err)
require.InDelta(t, costOne.ActualCost, costNeg.ActualCost, 1e-10)
}
func TestGetModelPricing_FallbackMatchesByFamily(t *testing.T) { func TestGetModelPricing_FallbackMatchesByFamily(t *testing.T) {
svc := newTestBillingService() svc := newTestBillingService()
@ -151,15 +123,6 @@ func TestGetModelPricing_UnknownOpenAIModelReturnsError(t *testing.T) {
require.Contains(t, err.Error(), "pricing not found") require.Contains(t, err.Error(), "pricing not found")
} }
func TestGetModelPricing_OpenAIGPT51Fallback(t *testing.T) {
svc := newTestBillingService()
pricing, err := svc.GetModelPricing("gpt-5.1")
require.NoError(t, err)
require.NotNil(t, pricing)
require.InDelta(t, 1.25e-6, pricing.InputPricePerToken, 1e-12)
}
func TestGetModelPricing_OpenAIGPT54Fallback(t *testing.T) { func TestGetModelPricing_OpenAIGPT54Fallback(t *testing.T) {
svc := newTestBillingService() svc := newTestBillingService()
@ -186,18 +149,6 @@ func TestGetModelPricing_OpenAIGPT54MiniFallback(t *testing.T) {
require.Zero(t, pricing.LongContextInputThreshold) require.Zero(t, pricing.LongContextInputThreshold)
} }
func TestGetModelPricing_OpenAIGPT54NanoFallback(t *testing.T) {
svc := newTestBillingService()
pricing, err := svc.GetModelPricing("gpt-5.4-nano")
require.NoError(t, err)
require.NotNil(t, pricing)
require.InDelta(t, 2e-7, pricing.InputPricePerToken, 1e-12)
require.InDelta(t, 1.25e-6, pricing.OutputPricePerToken, 1e-12)
require.InDelta(t, 2e-8, pricing.CacheReadPricePerToken, 1e-12)
require.Zero(t, pricing.LongContextInputThreshold)
}
func TestCalculateCost_OpenAIGPT54LongContextAppliesWholeSessionMultipliers(t *testing.T) { func TestCalculateCost_OpenAIGPT54LongContextAppliesWholeSessionMultipliers(t *testing.T) {
svc := newTestBillingService() svc := newTestBillingService()
@ -232,13 +183,13 @@ func TestGetFallbackPricing_FamilyMatching(t *testing.T) {
{name: "claude generic model fallback sonnet", model: "claude-foo-bar", expectedInput: 3e-6}, {name: "claude generic model fallback sonnet", model: "claude-foo-bar", expectedInput: 3e-6},
{name: "gemini explicit fallback", model: "gemini-3-1-pro", expectedInput: 2e-6}, {name: "gemini explicit fallback", model: "gemini-3-1-pro", expectedInput: 2e-6},
{name: "gemini unknown no fallback", model: "gemini-2.0-pro", expectNilPricing: true}, {name: "gemini unknown no fallback", model: "gemini-2.0-pro", expectNilPricing: true},
{name: "openai gpt5.1", model: "gpt-5.1", expectedInput: 1.25e-6},
{name: "openai gpt5.4", model: "gpt-5.4", expectedInput: 2.5e-6}, {name: "openai gpt5.4", model: "gpt-5.4", expectedInput: 2.5e-6},
{name: "openai gpt5.4 mini", model: "gpt-5.4-mini", expectedInput: 7.5e-7}, {name: "openai gpt5.4 mini", model: "gpt-5.4-mini", expectedInput: 7.5e-7},
{name: "openai gpt5.4 nano", model: "gpt-5.4-nano", expectedInput: 2e-7},
{name: "openai gpt5.3 codex", model: "gpt-5.3-codex", expectedInput: 1.5e-6}, {name: "openai gpt5.3 codex", model: "gpt-5.3-codex", expectedInput: 1.5e-6},
{name: "openai gpt5.1 codex max alias", model: "gpt-5.1-codex-max", expectedInput: 1.5e-6}, {name: "openai gpt5.3 codex spark", model: "gpt-5.3-codex-spark", expectedInput: 1.5e-6},
{name: "openai codex mini latest alias", model: "codex-mini-latest", expectedInput: 1.5e-6}, {name: "openai legacy gpt5.1 falls back to gpt5.4", model: "gpt-5.1", expectedInput: 2.5e-6},
{name: "openai legacy gpt5.1 codex falls back to gpt5.3 codex", model: "gpt-5.1-codex", expectedInput: 1.5e-6},
{name: "openai legacy codex mini latest falls back to gpt5.3 codex", model: "codex-mini-latest", expectedInput: 1.5e-6},
{name: "openai unknown no fallback", model: "gpt-unknown-model", expectNilPricing: true}, {name: "openai unknown no fallback", model: "gpt-unknown-model", expectNilPricing: true},
{name: "non supported family", model: "qwen-max", expectNilPricing: true}, {name: "non supported family", model: "qwen-max", expectNilPricing: true},
} }

View File

@ -147,40 +147,35 @@ func TestCalculateCostUnified_ImageMode(t *testing.T) {
require.Equal(t, string(BillingModeImage), cost.BillingMode) require.Equal(t, string(BillingModeImage), cost.BillingMode)
} }
func TestCalculateCostUnified_RateMultiplierZeroDefaultsToOne(t *testing.T) { // TestCalculateCostUnified_RateMultiplierZeroProducesZero 锁定新行为:
// 保存时强制 > 0若 0 仍泄漏到计费层,按 0 计费(而非历史上的 1.0)。
func TestCalculateCostUnified_RateMultiplierZeroProducesZero(t *testing.T) {
bs := newTestBillingService() bs := newTestBillingService()
resolver := NewModelPricingResolver(nil, bs) resolver := NewModelPricingResolver(nil, bs)
tokens := UsageTokens{InputTokens: 1000, OutputTokens: 500} tokens := UsageTokens{InputTokens: 1000, OutputTokens: 500}
costZero, err := bs.CalculateCostUnified(CostInput{ cost, err := bs.CalculateCostUnified(CostInput{
Ctx: context.Background(), Ctx: context.Background(),
Model: "claude-sonnet-4", Model: "claude-sonnet-4",
Tokens: tokens, Tokens: tokens,
RateMultiplier: 0, // should default to 1.0 RateMultiplier: 0,
Resolver: resolver, Resolver: resolver,
}) })
require.NoError(t, err) require.NoError(t, err)
require.Greater(t, cost.TotalCost, 0.0)
costOne, err := bs.CalculateCostUnified(CostInput{ require.InDelta(t, 0.0, cost.ActualCost, 1e-10)
Ctx: context.Background(),
Model: "claude-sonnet-4",
Tokens: tokens,
RateMultiplier: 1.0,
Resolver: resolver,
})
require.NoError(t, err)
require.InDelta(t, costOne.ActualCost, costZero.ActualCost, 1e-10)
} }
func TestCalculateCostUnified_NegativeRateMultiplierDefaultsToOne(t *testing.T) { // TestCalculateCostUnified_NegativeRateMultiplierClampedToZero 锁定新行为:
// 负数倍率按 0 计费,避免历史的 <=0 → 1.0 把配置异常静默按标准价扣费。
func TestCalculateCostUnified_NegativeRateMultiplierClampedToZero(t *testing.T) {
bs := newTestBillingService() bs := newTestBillingService()
resolver := NewModelPricingResolver(nil, bs) resolver := NewModelPricingResolver(nil, bs)
tokens := UsageTokens{InputTokens: 1000} tokens := UsageTokens{InputTokens: 1000}
costNeg, err := bs.CalculateCostUnified(CostInput{ cost, err := bs.CalculateCostUnified(CostInput{
Ctx: context.Background(), Ctx: context.Background(),
Model: "claude-sonnet-4", Model: "claude-sonnet-4",
Tokens: tokens, Tokens: tokens,
@ -188,17 +183,8 @@ func TestCalculateCostUnified_NegativeRateMultiplierDefaultsToOne(t *testing.T)
Resolver: resolver, Resolver: resolver,
}) })
require.NoError(t, err) require.NoError(t, err)
require.Greater(t, cost.TotalCost, 0.0)
costOne, err := bs.CalculateCostUnified(CostInput{ require.InDelta(t, 0.0, cost.ActualCost, 1e-10)
Ctx: context.Background(),
Model: "claude-sonnet-4",
Tokens: tokens,
RateMultiplier: 1.0,
Resolver: resolver,
})
require.NoError(t, err)
require.InDelta(t, costOne.ActualCost, costNeg.ActualCost, 1e-10)
} }
func TestCalculateCostUnified_BillingModeFieldFilled(t *testing.T) { func TestCalculateCostUnified_BillingModeFieldFilled(t *testing.T) {

View File

@ -962,7 +962,7 @@ func NormalizeClaudeOutputEffort(raw string) *string {
return nil return nil
} }
switch value { switch value {
case "low", "medium", "high", "max": case "low", "medium", "high", "xhigh", "max":
return &value return &value
default: default:
return nil return nil

View File

@ -1149,6 +1149,11 @@ func TestParseGatewayRequest_OutputEffort(t *testing.T) {
body: `{"model":"claude-opus-4-6","output_config":{"effort":"max"},"messages":[]}`, body: `{"model":"claude-opus-4-6","output_config":{"effort":"max"},"messages":[]}`,
wantEffort: "max", wantEffort: "max",
}, },
{
name: "output_config.effort xhigh",
body: `{"model":"claude-opus-4-7","output_config":{"effort":"xhigh"},"messages":[]}`,
wantEffort: "xhigh",
},
{ {
name: "output_config without effort", name: "output_config without effort",
body: `{"model":"claude-opus-4-6","output_config":{},"messages":[]}`, body: `{"model":"claude-opus-4-6","output_config":{},"messages":[]}`,
@ -1186,9 +1191,10 @@ func TestNormalizeClaudeOutputEffort(t *testing.T) {
{"LOW", strPtr("low")}, {"LOW", strPtr("low")},
{"Max", strPtr("max")}, {"Max", strPtr("max")},
{" medium ", strPtr("medium")}, {" medium ", strPtr("medium")},
{"xhigh", strPtr("xhigh")},
{"XHIGH", strPtr("xhigh")},
{"", nil}, {"", nil},
{"unknown", nil}, {"unknown", nil},
{"xhigh", nil},
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.input, func(t *testing.T) { t.Run(tt.input, func(t *testing.T) {

View File

@ -435,26 +435,19 @@ func prefetchedStickyAccountIDFromContext(ctx context.Context, groupID *int64) i
} }
// shouldClearStickySession 检查账号是否处于不可调度状态,需要清理粘性会话绑定。 // shouldClearStickySession 检查账号是否处于不可调度状态,需要清理粘性会话绑定。
// 当账号状态为错误、禁用、不可调度、处于临时不可调度期间, // 委托 IsSchedulable() 判断账号级可调度性(状态、配额、过载、限流等),
// 或请求的模型处于限流状态时,返回 true。 // 额外检查模型级限流。
// 这确保后续请求不会继续使用不可用的账号。
// //
// shouldClearStickySession checks if an account is in an unschedulable state // shouldClearStickySession checks if an account is in an unschedulable state
// and the sticky session binding should be cleared. // and the sticky session binding should be cleared.
// Returns true when account status is error/disabled, schedulable is false, // Delegates to IsSchedulable() for account-level checks, plus model-level rate limiting.
// within temporary unschedulable period, or the requested model is rate-limited.
// This ensures subsequent requests won't continue using unavailable accounts.
func shouldClearStickySession(account *Account, requestedModel string) bool { func shouldClearStickySession(account *Account, requestedModel string) bool {
if account == nil { if account == nil {
return false return false
} }
if account.Status == StatusError || account.Status == StatusDisabled || !account.Schedulable { if !account.IsSchedulable() {
return true return true
} }
if account.TempUnschedulableUntil != nil && time.Now().Before(*account.TempUnschedulableUntil) {
return true
}
// 检查模型限流和 scope 限流,有限流即清除粘性会话
if remaining := account.GetRateLimitRemainingTimeWithContext(context.Background(), requestedModel); remaining > 0 { if remaining := account.GetRateLimitRemainingTimeWithContext(context.Background(), requestedModel); remaining > 0 {
return true return true
} }
@ -7317,8 +7310,10 @@ func postUsageBilling(ctx context.Context, p *postUsageBillingParams, deps *bill
cost := p.Cost cost := p.Cost
if p.IsSubscriptionBill { if p.IsSubscriptionBill {
if cost.TotalCost > 0 { // Subscription usage tracked by ActualCost so group rate multiplier
if err := deps.userSubRepo.IncrementUsage(billingCtx, p.Subscription.ID, cost.TotalCost); err != nil { // consumes the quota at the expected speed.
if cost.ActualCost > 0 {
if err := deps.userSubRepo.IncrementUsage(billingCtx, p.Subscription.ID, cost.ActualCost); err != nil {
slog.Error("increment subscription usage failed", "subscription_id", p.Subscription.ID, "error", err) slog.Error("increment subscription usage failed", "subscription_id", p.Subscription.ID, "error", err)
} }
} }
@ -7417,9 +7412,13 @@ func buildUsageBillingCommand(requestID string, usageLog *UsageLog, p *postUsage
} }
} }
// Record subscription / balance cost using ActualCost so the group (and any
// user-specific) rate multiplier consumes subscription quota at the expected
// speed. TotalCost remains the raw (pre-multiplier) value; downstream guards
// on "> 0" still correctly skip free subscriptions (RateMultiplier == 0).
if p.IsSubscriptionBill && p.Subscription != nil && p.Cost.TotalCost > 0 { if p.IsSubscriptionBill && p.Subscription != nil && p.Cost.TotalCost > 0 {
cmd.SubscriptionID = &p.Subscription.ID cmd.SubscriptionID = &p.Subscription.ID
cmd.SubscriptionCost = p.Cost.TotalCost cmd.SubscriptionCost = p.Cost.ActualCost
} else if p.Cost.ActualCost > 0 { } else if p.Cost.ActualCost > 0 {
cmd.BalanceCost = p.Cost.ActualCost cmd.BalanceCost = p.Cost.ActualCost
} }
@ -7478,8 +7477,8 @@ func finalizePostUsageBilling(p *postUsageBillingParams, deps *billingDeps, resu
} }
if p.IsSubscriptionBill { if p.IsSubscriptionBill {
if p.Cost.TotalCost > 0 && p.User != nil && p.APIKey != nil && p.APIKey.GroupID != nil { if p.Cost.ActualCost > 0 && p.User != nil && p.APIKey != nil && p.APIKey.GroupID != nil {
deps.billingCacheService.QueueUpdateSubscriptionUsage(p.User.ID, *p.APIKey.GroupID, p.Cost.TotalCost) deps.billingCacheService.QueueUpdateSubscriptionUsage(p.User.ID, *p.APIKey.GroupID, p.Cost.ActualCost)
} }
} else if p.Cost.ActualCost > 0 && p.User != nil { } else if p.Cost.ActualCost > 0 && p.User != nil {
deps.billingCacheService.QueueDeductBalance(p.User.ID, p.Cost.ActualCost) deps.billingCacheService.QueueDeductBalance(p.User.ID, p.Cost.ActualCost)

View File

@ -0,0 +1,85 @@
//go:build unit
package service
import (
"testing"
)
// TestBuildUsageBillingCommand_SubscriptionAppliesRateMultiplier locks in the fix
// that subscription-mode billing honours the group (and any user-specific) rate
// multiplier — i.e. cmd.SubscriptionCost tracks ActualCost (= TotalCost *
// RateMultiplier), not raw TotalCost.
func TestBuildUsageBillingCommand_SubscriptionAppliesRateMultiplier(t *testing.T) {
t.Parallel()
groupID := int64(7)
subID := int64(42)
tests := []struct {
name string
totalCost float64
actualCost float64
isSubscription bool
wantSub float64
wantBalance float64
}{
{
name: "subscription with 2x multiplier consumes 2x quota",
totalCost: 1.0,
actualCost: 2.0,
isSubscription: true,
wantSub: 2.0,
wantBalance: 0,
},
{
name: "subscription with 0.5x multiplier consumes 0.5x quota",
totalCost: 1.0,
actualCost: 0.5,
isSubscription: true,
wantSub: 0.5,
wantBalance: 0,
},
{
name: "free subscription (multiplier 0) consumes no quota",
totalCost: 1.0,
actualCost: 0,
isSubscription: true,
wantSub: 0,
wantBalance: 0,
},
{
name: "balance billing keeps using ActualCost (regression)",
totalCost: 1.0,
actualCost: 2.0,
isSubscription: false,
wantSub: 0,
wantBalance: 2.0,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
p := &postUsageBillingParams{
Cost: &CostBreakdown{TotalCost: tt.totalCost, ActualCost: tt.actualCost},
User: &User{ID: 1},
APIKey: &APIKey{ID: 2, GroupID: &groupID},
Account: &Account{ID: 3},
Subscription: &UserSubscription{ID: subID},
IsSubscriptionBill: tt.isSubscription,
}
cmd := buildUsageBillingCommand("req-1", nil, p)
if cmd == nil {
t.Fatal("buildUsageBillingCommand returned nil")
}
if cmd.SubscriptionCost != tt.wantSub {
t.Errorf("SubscriptionCost = %v, want %v", cmd.SubscriptionCost, tt.wantSub)
}
if cmd.BalanceCost != tt.wantBalance {
t.Errorf("BalanceCost = %v, want %v", cmd.BalanceCost, tt.wantBalance)
}
})
}
}

View File

@ -76,10 +76,6 @@ func (g *Group) IsSubscriptionType() bool {
return g.SubscriptionType == SubscriptionTypeSubscription return g.SubscriptionType == SubscriptionTypeSubscription
} }
func (g *Group) IsFreeSubscription() bool {
return g.IsSubscriptionType() && g.RateMultiplier == 0
}
func (g *Group) HasDailyLimit() bool { func (g *Group) HasDailyLimit() bool {
return g.DailyLimitUSD != nil && *g.DailyLimitUSD > 0 return g.DailyLimitUSD != nil && *g.DailyLimitUSD > 0
} }

View File

@ -8,7 +8,6 @@ import (
var codexModelMap = map[string]string{ var codexModelMap = map[string]string{
"gpt-5.4": "gpt-5.4", "gpt-5.4": "gpt-5.4",
"gpt-5.4-mini": "gpt-5.4-mini", "gpt-5.4-mini": "gpt-5.4-mini",
"gpt-5.4-nano": "gpt-5.4-nano",
"gpt-5.4-none": "gpt-5.4", "gpt-5.4-none": "gpt-5.4",
"gpt-5.4-low": "gpt-5.4", "gpt-5.4-low": "gpt-5.4",
"gpt-5.4-medium": "gpt-5.4", "gpt-5.4-medium": "gpt-5.4",
@ -22,52 +21,21 @@ var codexModelMap = map[string]string{
"gpt-5.3-high": "gpt-5.3-codex", "gpt-5.3-high": "gpt-5.3-codex",
"gpt-5.3-xhigh": "gpt-5.3-codex", "gpt-5.3-xhigh": "gpt-5.3-codex",
"gpt-5.3-codex": "gpt-5.3-codex", "gpt-5.3-codex": "gpt-5.3-codex",
"gpt-5.3-codex-spark": "gpt-5.3-codex", "gpt-5.3-codex-spark": "gpt-5.3-codex-spark",
"gpt-5.3-codex-spark-low": "gpt-5.3-codex", "gpt-5.3-codex-spark-low": "gpt-5.3-codex-spark",
"gpt-5.3-codex-spark-medium": "gpt-5.3-codex", "gpt-5.3-codex-spark-medium": "gpt-5.3-codex-spark",
"gpt-5.3-codex-spark-high": "gpt-5.3-codex", "gpt-5.3-codex-spark-high": "gpt-5.3-codex-spark",
"gpt-5.3-codex-spark-xhigh": "gpt-5.3-codex", "gpt-5.3-codex-spark-xhigh": "gpt-5.3-codex-spark",
"gpt-5.3-codex-low": "gpt-5.3-codex", "gpt-5.3-codex-low": "gpt-5.3-codex",
"gpt-5.3-codex-medium": "gpt-5.3-codex", "gpt-5.3-codex-medium": "gpt-5.3-codex",
"gpt-5.3-codex-high": "gpt-5.3-codex", "gpt-5.3-codex-high": "gpt-5.3-codex",
"gpt-5.3-codex-xhigh": "gpt-5.3-codex", "gpt-5.3-codex-xhigh": "gpt-5.3-codex",
"gpt-5.1-codex": "gpt-5.1-codex",
"gpt-5.1-codex-low": "gpt-5.1-codex",
"gpt-5.1-codex-medium": "gpt-5.1-codex",
"gpt-5.1-codex-high": "gpt-5.1-codex",
"gpt-5.1-codex-max": "gpt-5.1-codex-max",
"gpt-5.1-codex-max-low": "gpt-5.1-codex-max",
"gpt-5.1-codex-max-medium": "gpt-5.1-codex-max",
"gpt-5.1-codex-max-high": "gpt-5.1-codex-max",
"gpt-5.1-codex-max-xhigh": "gpt-5.1-codex-max",
"gpt-5.2": "gpt-5.2", "gpt-5.2": "gpt-5.2",
"gpt-5.2-none": "gpt-5.2", "gpt-5.2-none": "gpt-5.2",
"gpt-5.2-low": "gpt-5.2", "gpt-5.2-low": "gpt-5.2",
"gpt-5.2-medium": "gpt-5.2", "gpt-5.2-medium": "gpt-5.2",
"gpt-5.2-high": "gpt-5.2", "gpt-5.2-high": "gpt-5.2",
"gpt-5.2-xhigh": "gpt-5.2", "gpt-5.2-xhigh": "gpt-5.2",
"gpt-5.2-codex": "gpt-5.2-codex",
"gpt-5.2-codex-low": "gpt-5.2-codex",
"gpt-5.2-codex-medium": "gpt-5.2-codex",
"gpt-5.2-codex-high": "gpt-5.2-codex",
"gpt-5.2-codex-xhigh": "gpt-5.2-codex",
"gpt-5.1-codex-mini": "gpt-5.1-codex-mini",
"gpt-5.1-codex-mini-medium": "gpt-5.1-codex-mini",
"gpt-5.1-codex-mini-high": "gpt-5.1-codex-mini",
"gpt-5.1": "gpt-5.1",
"gpt-5.1-none": "gpt-5.1",
"gpt-5.1-low": "gpt-5.1",
"gpt-5.1-medium": "gpt-5.1",
"gpt-5.1-high": "gpt-5.1",
"gpt-5.1-chat-latest": "gpt-5.1",
"gpt-5-codex": "gpt-5.1-codex",
"codex-mini-latest": "gpt-5.1-codex-mini",
"gpt-5-codex-mini": "gpt-5.1-codex-mini",
"gpt-5-codex-mini-medium": "gpt-5.1-codex-mini",
"gpt-5-codex-mini-high": "gpt-5.1-codex-mini",
"gpt-5": "gpt-5.1",
"gpt-5-mini": "gpt-5.1",
"gpt-5-nano": "gpt-5.1",
} }
type codexTransformResult struct { type codexTransformResult struct {
@ -220,7 +188,7 @@ func applyCodexOAuthTransform(reqBody map[string]any, isCodexCLI bool, isCompact
func normalizeCodexModel(model string) string { func normalizeCodexModel(model string) string {
if model == "" { if model == "" {
return "gpt-5.1" return "gpt-5.4"
} }
modelID := model modelID := model
@ -238,49 +206,29 @@ func normalizeCodexModel(model string) string {
if strings.Contains(normalized, "gpt-5.4-mini") || strings.Contains(normalized, "gpt 5.4 mini") { if strings.Contains(normalized, "gpt-5.4-mini") || strings.Contains(normalized, "gpt 5.4 mini") {
return "gpt-5.4-mini" return "gpt-5.4-mini"
} }
if strings.Contains(normalized, "gpt-5.4-nano") || strings.Contains(normalized, "gpt 5.4 nano") {
return "gpt-5.4-nano"
}
if strings.Contains(normalized, "gpt-5.4") || strings.Contains(normalized, "gpt 5.4") { if strings.Contains(normalized, "gpt-5.4") || strings.Contains(normalized, "gpt 5.4") {
return "gpt-5.4" return "gpt-5.4"
} }
if strings.Contains(normalized, "gpt-5.2-codex") || strings.Contains(normalized, "gpt 5.2 codex") {
return "gpt-5.2-codex"
}
if strings.Contains(normalized, "gpt-5.2") || strings.Contains(normalized, "gpt 5.2") { if strings.Contains(normalized, "gpt-5.2") || strings.Contains(normalized, "gpt 5.2") {
return "gpt-5.2" return "gpt-5.2"
} }
if strings.Contains(normalized, "gpt-5.3-codex-spark") || strings.Contains(normalized, "gpt 5.3 codex spark") {
return "gpt-5.3-codex-spark"
}
if strings.Contains(normalized, "gpt-5.3-codex") || strings.Contains(normalized, "gpt 5.3 codex") { if strings.Contains(normalized, "gpt-5.3-codex") || strings.Contains(normalized, "gpt 5.3 codex") {
return "gpt-5.3-codex" return "gpt-5.3-codex"
} }
if strings.Contains(normalized, "gpt-5.3") || strings.Contains(normalized, "gpt 5.3") { if strings.Contains(normalized, "gpt-5.3") || strings.Contains(normalized, "gpt 5.3") {
return "gpt-5.3-codex" return "gpt-5.3-codex"
} }
if strings.Contains(normalized, "gpt-5.1-codex-max") || strings.Contains(normalized, "gpt 5.1 codex max") {
return "gpt-5.1-codex-max"
}
if strings.Contains(normalized, "gpt-5.1-codex-mini") || strings.Contains(normalized, "gpt 5.1 codex mini") {
return "gpt-5.1-codex-mini"
}
if strings.Contains(normalized, "codex-mini-latest") ||
strings.Contains(normalized, "gpt-5-codex-mini") ||
strings.Contains(normalized, "gpt 5 codex mini") {
return "codex-mini-latest"
}
if strings.Contains(normalized, "gpt-5.1-codex") || strings.Contains(normalized, "gpt 5.1 codex") {
return "gpt-5.1-codex"
}
if strings.Contains(normalized, "gpt-5.1") || strings.Contains(normalized, "gpt 5.1") {
return "gpt-5.1"
}
if strings.Contains(normalized, "codex") { if strings.Contains(normalized, "codex") {
return "gpt-5.1-codex" return "gpt-5.3-codex"
} }
if strings.Contains(normalized, "gpt-5") || strings.Contains(normalized, "gpt 5") { if strings.Contains(normalized, "gpt-5") || strings.Contains(normalized, "gpt 5") {
return "gpt-5.1" return "gpt-5.4"
} }
return "gpt-5.1" return "gpt-5.4"
} }
func normalizeOpenAIModelForUpstream(account *Account, model string) string { func normalizeOpenAIModelForUpstream(account *Account, model string) string {

View File

@ -240,15 +240,13 @@ func TestNormalizeCodexModel_Gpt53(t *testing.T) {
"gpt 5.4": "gpt-5.4", "gpt 5.4": "gpt-5.4",
"gpt-5.4-mini": "gpt-5.4-mini", "gpt-5.4-mini": "gpt-5.4-mini",
"gpt 5.4 mini": "gpt-5.4-mini", "gpt 5.4 mini": "gpt-5.4-mini",
"gpt-5.4-nano": "gpt-5.4-nano",
"gpt 5.4 nano": "gpt-5.4-nano",
"gpt-5.3": "gpt-5.3-codex", "gpt-5.3": "gpt-5.3-codex",
"gpt-5.3-codex": "gpt-5.3-codex", "gpt-5.3-codex": "gpt-5.3-codex",
"gpt-5.3-codex-xhigh": "gpt-5.3-codex", "gpt-5.3-codex-xhigh": "gpt-5.3-codex",
"gpt-5.3-codex-spark": "gpt-5.3-codex", "gpt-5.3-codex-spark": "gpt-5.3-codex-spark",
"gpt 5.3 codex spark": "gpt-5.3-codex", "gpt 5.3 codex spark": "gpt-5.3-codex-spark",
"gpt-5.3-codex-spark-high": "gpt-5.3-codex", "gpt-5.3-codex-spark-high": "gpt-5.3-codex-spark",
"gpt-5.3-codex-spark-xhigh": "gpt-5.3-codex", "gpt-5.3-codex-spark-xhigh": "gpt-5.3-codex-spark",
"gpt 5.3 codex": "gpt-5.3-codex", "gpt 5.3 codex": "gpt-5.3-codex",
} }
@ -257,6 +255,26 @@ func TestNormalizeCodexModel_Gpt53(t *testing.T) {
} }
} }
func TestNormalizeCodexModel_RemovedModelsFallbackToSupportedTargets(t *testing.T) {
cases := map[string]string{
"": "gpt-5.4",
"gpt-5": "gpt-5.4",
"gpt-5-mini": "gpt-5.4",
"gpt-5-nano": "gpt-5.4",
"gpt-5.1": "gpt-5.4",
"gpt-5.1-codex": "gpt-5.3-codex",
"gpt-5.1-codex-max": "gpt-5.3-codex",
"gpt-5.1-codex-mini": "gpt-5.3-codex",
"gpt-5.2-codex": "gpt-5.2",
"codex-mini-latest": "gpt-5.3-codex",
"gpt-5-codex": "gpt-5.3-codex",
}
for input, expected := range cases {
require.Equal(t, expected, normalizeCodexModel(input))
}
}
func TestApplyCodexOAuthTransform_PreservesBareSparkModel(t *testing.T) { func TestApplyCodexOAuthTransform_PreservesBareSparkModel(t *testing.T) {
reqBody := map[string]any{ reqBody := map[string]any{
"model": "gpt-5.3-codex-spark", "model": "gpt-5.3-codex-spark",

View File

@ -10,8 +10,14 @@ import (
const compatPromptCacheKeyPrefix = "compat_cc_" const compatPromptCacheKeyPrefix = "compat_cc_"
func shouldAutoInjectPromptCacheKeyForCompat(model string) bool { func shouldAutoInjectPromptCacheKeyForCompat(model string) bool {
switch normalizeCodexModel(strings.TrimSpace(model)) { trimmed := strings.TrimSpace(strings.ToLower(model))
case "gpt-5.4", "gpt-5.3-codex": // 仅对 Codex OAuth 路径支持的 GPT-5 族开启自动注入,避免 normalizeCodexModel
// 的默认兜底把任意模型(如 gpt-4o、claude-*)误判为 gpt-5.4。
if !strings.Contains(trimmed, "gpt-5") && !strings.Contains(trimmed, "codex") {
return false
}
switch normalizeCodexModel(trimmed) {
case "gpt-5.4", "gpt-5.3-codex", "gpt-5.3-codex-spark":
return true return true
default: default:
return false return false

View File

@ -1031,7 +1031,7 @@ func TestOpenAIGatewayServiceRecordUsage_SubscriptionBillingSetsSubscriptionFiel
Model: "gpt-5.1", Model: "gpt-5.1",
Duration: time.Second, Duration: time.Second,
}, },
APIKey: &APIKey{ID: 100, GroupID: i64p(88), Group: &Group{ID: 88, SubscriptionType: SubscriptionTypeSubscription}}, APIKey: &APIKey{ID: 100, GroupID: i64p(88), Group: &Group{ID: 88, SubscriptionType: SubscriptionTypeSubscription, RateMultiplier: 1.0}},
User: &User{ID: 200}, User: &User{ID: 200},
Account: &Account{ID: 300}, Account: &Account{ID: 300},
Subscription: subscription, Subscription: subscription,

View File

@ -69,14 +69,14 @@ func TestResolveOpenAIForwardModel(t *testing.T) {
} }
} }
func TestResolveOpenAIForwardModel_PreventsClaudeModelFromFallingBackToGpt51(t *testing.T) { func TestResolveOpenAIForwardModel_PreventsClaudeModelFromFallingBackToGpt54(t *testing.T) {
account := &Account{ account := &Account{
Credentials: map[string]any{}, Credentials: map[string]any{},
} }
withoutDefault := normalizeCodexModel(resolveOpenAIForwardModel(account, "claude-opus-4-6", "")) withoutDefault := normalizeCodexModel(resolveOpenAIForwardModel(account, "claude-opus-4-6", ""))
if withoutDefault != "gpt-5.1" { if withoutDefault != "gpt-5.4" {
t.Fatalf("normalizeCodexModel(...) = %q, want %q", withoutDefault, "gpt-5.1") t.Fatalf("normalizeCodexModel(...) = %q, want %q", withoutDefault, "gpt-5.4")
} }
withDefault := normalizeCodexModel(resolveOpenAIForwardModel(account, "claude-opus-4-6", "gpt-5.4")) withDefault := normalizeCodexModel(resolveOpenAIForwardModel(account, "claude-opus-4-6", "gpt-5.4"))
@ -87,9 +87,9 @@ func TestResolveOpenAIForwardModel_PreventsClaudeModelFromFallingBackToGpt51(t *
func TestNormalizeCodexModel(t *testing.T) { func TestNormalizeCodexModel(t *testing.T) {
cases := map[string]string{ cases := map[string]string{
"gpt-5.3-codex-spark": "gpt-5.3-codex", "gpt-5.3-codex-spark": "gpt-5.3-codex-spark",
"gpt-5.3-codex-spark-high": "gpt-5.3-codex", "gpt-5.3-codex-spark-high": "gpt-5.3-codex-spark",
"gpt-5.3-codex-spark-xhigh": "gpt-5.3-codex", "gpt-5.3-codex-spark-xhigh": "gpt-5.3-codex-spark",
"gpt-5.3": "gpt-5.3-codex", "gpt-5.3": "gpt-5.3-codex",
} }
@ -111,7 +111,7 @@ func TestNormalizeOpenAIModelForUpstream(t *testing.T) {
name: "oauth keeps codex normalization behavior", name: "oauth keeps codex normalization behavior",
account: &Account{Type: AccountTypeOAuth}, account: &Account{Type: AccountTypeOAuth},
model: "gemini-3-flash-preview", model: "gemini-3-flash-preview",
want: "gpt-5.1", want: "gpt-5.4",
}, },
{ {
name: "apikey preserves custom compatible model", name: "apikey preserves custom compatible model",

View File

@ -4,6 +4,7 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"log/slog"
"strconv" "strconv"
"strings" "strings"
@ -11,9 +12,22 @@ import (
"github.com/Wei-Shaw/sub2api/ent/paymentorder" "github.com/Wei-Shaw/sub2api/ent/paymentorder"
"github.com/Wei-Shaw/sub2api/ent/paymentproviderinstance" "github.com/Wei-Shaw/sub2api/ent/paymentproviderinstance"
"github.com/Wei-Shaw/sub2api/internal/payment" "github.com/Wei-Shaw/sub2api/internal/payment"
"github.com/Wei-Shaw/sub2api/internal/payment/provider"
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
) )
// validateProviderConfig runs the provider's constructor to surface config-level
// errors at save time (e.g. wxpay missing certSerial), instead of only failing
// when an order is created. Returns the structured ApplicationError from the
// constructor so the frontend i18n layer can localize it.
//
// Only validates enabled instances — a disabled instance may be a half-filled
// draft the admin will complete later.
func (s *PaymentConfigService) validateProviderConfig(providerKey string, config map[string]string) error {
_, err := provider.CreateProvider(providerKey, "_validate_", config)
return err
}
// --- Provider Instance CRUD --- // --- Provider Instance CRUD ---
func (s *PaymentConfigService) ListProviderInstances(ctx context.Context) ([]*dbent.PaymentProviderInstance, error) { func (s *PaymentConfigService) ListProviderInstances(ctx context.Context) ([]*dbent.PaymentProviderInstance, error) {
@ -47,11 +61,10 @@ func (s *PaymentConfigService) ListProviderInstancesWithConfig(ctx context.Conte
resp := ProviderInstanceResponse{ resp := ProviderInstanceResponse{
ID: int64(inst.ID), ProviderKey: inst.ProviderKey, Name: inst.Name, ID: int64(inst.ID), ProviderKey: inst.ProviderKey, Name: inst.Name,
SupportedTypes: splitTypes(inst.SupportedTypes), Limits: inst.Limits, SupportedTypes: splitTypes(inst.SupportedTypes), Limits: inst.Limits,
Enabled: inst.Enabled, RefundEnabled: inst.RefundEnabled, Enabled: inst.Enabled, RefundEnabled: inst.RefundEnabled, AllowUserRefund: inst.AllowUserRefund,
AllowUserRefund: inst.AllowUserRefund, SortOrder: inst.SortOrder, PaymentMode: inst.PaymentMode,
SortOrder: inst.SortOrder, PaymentMode: inst.PaymentMode,
} }
resp.Config, err = s.decryptAndMaskConfig(inst.Config) resp.Config, err = s.decryptAndMaskConfig(inst.ProviderKey, inst.Config)
if err != nil { if err != nil {
return nil, fmt.Errorf("decrypt config for instance %d: %w", inst.ID, err) return nil, fmt.Errorf("decrypt config for instance %d: %w", inst.ID, err)
} }
@ -60,8 +73,26 @@ func (s *PaymentConfigService) ListProviderInstancesWithConfig(ctx context.Conte
return result, nil return result, nil
} }
func (s *PaymentConfigService) decryptAndMaskConfig(encrypted string) (map[string]string, error) { // decryptAndMaskConfig returns the stored config with sensitive fields omitted.
return s.decryptConfig(encrypted) // Admin UIs display masked placeholders for these; the raw values never leave
// the server. Callers that need the full config (e.g. payment runtime) must
// use decryptConfig directly.
func (s *PaymentConfigService) decryptAndMaskConfig(providerKey, encrypted string) (map[string]string, error) {
cfg, err := s.decryptConfig(encrypted)
if err != nil {
return nil, err
}
if cfg == nil {
return nil, nil
}
masked := make(map[string]string, len(cfg))
for k, v := range cfg {
if isSensitiveProviderConfigField(providerKey, k) {
continue
}
masked[k] = v
}
return masked, nil
} }
// pendingOrderStatuses are order statuses considered "in progress". // pendingOrderStatuses are order statuses considered "in progress".
@ -71,16 +102,27 @@ var pendingOrderStatuses = []string{
payment.OrderStatusRecharging, payment.OrderStatusRecharging,
} }
var sensitiveConfigPatterns = []string{"key", "pkey", "secret", "private", "password"} // providerSensitiveConfigFields is the authoritative list of config keys that
// are treated as secrets per provider. Must stay in sync with the frontend
// definition at frontend/src/components/payment/providerConfig.ts
// (PROVIDER_CONFIG_FIELDS, fields with sensitive: true).
//
// Key matching is case-insensitive. Non-listed keys (e.g. appId, notifyUrl,
// stripe publishableKey) are returned in plaintext by the admin GET API.
var providerSensitiveConfigFields = map[string]map[string]struct{}{
payment.TypeEasyPay: {"pkey": {}},
payment.TypeAlipay: {"privatekey": {}, "publickey": {}, "alipaypublickey": {}},
payment.TypeWxpay: {"privatekey": {}, "apiv3key": {}, "publickey": {}},
payment.TypeStripe: {"secretkey": {}, "webhooksecret": {}},
}
func isSensitiveConfigField(fieldName string) bool { func isSensitiveProviderConfigField(providerKey, fieldName string) bool {
lower := strings.ToLower(fieldName) fields, ok := providerSensitiveConfigFields[providerKey]
for _, p := range sensitiveConfigPatterns { if !ok {
if strings.Contains(lower, p) { return false
return true
}
} }
return false _, found := fields[strings.ToLower(fieldName)]
return found
} }
func (s *PaymentConfigService) countPendingOrders(ctx context.Context, providerInstanceID int64) (int, error) { func (s *PaymentConfigService) countPendingOrders(ctx context.Context, providerInstanceID int64) (int, error) {
@ -111,6 +153,11 @@ func (s *PaymentConfigService) CreateProviderInstance(ctx context.Context, req C
if err := s.validateVisibleMethodEnablementConflicts(ctx, 0, req.ProviderKey, typesStr, req.Enabled); err != nil { if err := s.validateVisibleMethodEnablementConflicts(ctx, 0, req.ProviderKey, typesStr, req.Enabled); err != nil {
return nil, err return nil, err
} }
if req.Enabled {
if err := s.validateProviderConfig(req.ProviderKey, req.Config); err != nil {
return nil, err
}
}
enc, err := s.encryptConfig(req.Config) enc, err := s.encryptConfig(req.Config)
if err != nil { if err != nil {
return nil, err return nil, err
@ -141,7 +188,7 @@ func validateProviderRequest(providerKey, name, supportedTypes string) error {
func (s *PaymentConfigService) UpdateProviderInstance(ctx context.Context, id int64, req UpdateProviderInstanceRequest) (*dbent.PaymentProviderInstance, error) { func (s *PaymentConfigService) UpdateProviderInstance(ctx context.Context, id int64, req UpdateProviderInstanceRequest) (*dbent.PaymentProviderInstance, error) {
current, err := s.entClient.PaymentProviderInstance.Get(ctx, id) current, err := s.entClient.PaymentProviderInstance.Get(ctx, id)
if err != nil { if err != nil {
return nil, err return nil, fmt.Errorf("load provider instance: %w", err)
} }
nextEnabled := current.Enabled nextEnabled := current.Enabled
if req.Enabled != nil { if req.Enabled != nil {
@ -156,8 +203,8 @@ func (s *PaymentConfigService) UpdateProviderInstance(ctx context.Context, id in
} }
if req.Config != nil { if req.Config != nil {
hasSensitive := false hasSensitive := false
for k := range req.Config { for k, v := range req.Config {
if isSensitiveConfigField(k) && req.Config[k] != "" { if v != "" && isSensitiveProviderConfigField(current.ProviderKey, k) {
hasSensitive = true hasSensitive = true
break break
} }
@ -183,16 +230,38 @@ func (s *PaymentConfigService) UpdateProviderInstance(ctx context.Context, id in
WithMetadata(map[string]string{"count": strconv.Itoa(count)}) WithMetadata(map[string]string{"count": strconv.Itoa(count)})
} }
} }
// Validate merged config when the instance will end up enabled.
// This surfaces provider-level errors (e.g. wxpay missing certSerial) at save time,
// so admins see them in the dialog instead of only when an order is created.
finalEnabled := current.Enabled
if req.Enabled != nil {
finalEnabled = *req.Enabled
}
var mergedConfig map[string]string
if req.Config != nil {
mergedConfig, err = s.mergeConfig(ctx, id, req.Config)
if err != nil {
return nil, err
}
}
if finalEnabled {
configToValidate := mergedConfig
if configToValidate == nil {
configToValidate, err = s.decryptConfig(current.Config)
if err != nil {
return nil, fmt.Errorf("decrypt existing config: %w", err)
}
}
if err := s.validateProviderConfig(current.ProviderKey, configToValidate); err != nil {
return nil, err
}
}
u := s.entClient.PaymentProviderInstance.UpdateOneID(id) u := s.entClient.PaymentProviderInstance.UpdateOneID(id)
if req.Name != nil { if req.Name != nil {
u.SetName(*req.Name) u.SetName(*req.Name)
} }
if req.Config != nil { if mergedConfig != nil {
merged, err := s.mergeConfig(ctx, id, req.Config) enc, err := s.encryptConfig(mergedConfig)
if err != nil {
return nil, err
}
enc, err := s.encryptConfig(merged)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -293,27 +362,48 @@ func (s *PaymentConfigService) mergeConfig(ctx context.Context, id int64, newCon
return nil, fmt.Errorf("decrypt existing config for instance %d: %w", id, err) return nil, fmt.Errorf("decrypt existing config for instance %d: %w", id, err)
} }
if existing == nil { if existing == nil {
return newConfig, nil existing = map[string]string{}
} }
for k, v := range newConfig { for k, v := range newConfig {
// Preserve existing secrets when the client submits an empty value
// (admin UI omits the value to indicate "leave unchanged").
if v == "" && isSensitiveProviderConfigField(inst.ProviderKey, k) {
continue
}
existing[k] = v existing[k] = v
} }
return existing, nil return existing, nil
} }
func (s *PaymentConfigService) decryptConfig(encrypted string) (map[string]string, error) { // decryptConfig parses a stored provider config.
if encrypted == "" { // New records are plaintext JSON; legacy records are AES-256-GCM ciphertext
// ("iv:authTag:ciphertext"). Values that cannot be parsed as either — including
// legacy ciphertext with no/invalid TOTP_ENCRYPTION_KEY — are treated as empty,
// letting the admin re-enter the config via the UI to complete the migration.
//
// TODO(deprecated-legacy-ciphertext): The AES fallback branch is a transitional
// shim for pre-plaintext records. Remove it (and the encryptionKey field) after
// a few releases once all live deployments have re-saved their provider configs.
func (s *PaymentConfigService) decryptConfig(stored string) (map[string]string, error) {
if stored == "" {
return nil, nil return nil, nil
} }
decrypted, err := payment.Decrypt(encrypted, s.encryptionKey) var cfg map[string]string
if err != nil { if err := json.Unmarshal([]byte(stored), &cfg); err == nil {
return nil, fmt.Errorf("decrypt config: %w", err) return cfg, nil
} }
var raw map[string]string // Deprecated: legacy AES-256-GCM ciphertext fallback — scheduled for removal.
if err := json.Unmarshal([]byte(decrypted), &raw); err != nil { if len(s.encryptionKey) == payment.AES256KeySize {
return nil, fmt.Errorf("unmarshal decrypted config: %w", err) //nolint:staticcheck // SA1019: intentional legacy fallback, scheduled for removal
if plaintext, err := payment.Decrypt(stored, s.encryptionKey); err == nil {
if err := json.Unmarshal([]byte(plaintext), &cfg); err == nil {
return cfg, nil
}
}
} }
return raw, nil slog.Warn("payment provider config unreadable, treating as empty for re-entry",
"stored_len", len(stored))
return nil, nil
} }
func (s *PaymentConfigService) DeleteProviderInstance(ctx context.Context, id int64) error { func (s *PaymentConfigService) DeleteProviderInstance(ctx context.Context, id int64) error {
@ -328,14 +418,13 @@ func (s *PaymentConfigService) DeleteProviderInstance(ctx context.Context, id in
return s.entClient.PaymentProviderInstance.DeleteOneID(id).Exec(ctx) return s.entClient.PaymentProviderInstance.DeleteOneID(id).Exec(ctx)
} }
// encryptConfig serialises a provider config for storage.
// New records are written as plaintext JSON; the historical AES-GCM wrapping
// has been dropped but decryptConfig still accepts old ciphertext during migration.
func (s *PaymentConfigService) encryptConfig(cfg map[string]string) (string, error) { func (s *PaymentConfigService) encryptConfig(cfg map[string]string) (string, error) {
data, err := json.Marshal(cfg) data, err := json.Marshal(cfg)
if err != nil { if err != nil {
return "", fmt.Errorf("marshal config: %w", err) return "", fmt.Errorf("marshal config: %w", err)
} }
enc, err := payment.Encrypt(string(data), s.encryptionKey) return string(data), nil
if err != nil {
return "", fmt.Errorf("encrypt config: %w", err)
}
return enc, nil
} }

View File

@ -99,41 +99,52 @@ func TestValidateProviderRequest(t *testing.T) {
} }
} }
func TestIsSensitiveConfigField(t *testing.T) { func TestIsSensitiveProviderConfigField(t *testing.T) {
t.Parallel() t.Parallel()
tests := []struct { tests := []struct {
field string providerKey string
wantSen bool field string
wantSen bool
}{ }{
// Sensitive fields (contain key/secret/private/password/pkey patterns) // Stripe: publishableKey is public, only secretKey/webhookSecret are secrets
{"secretKey", true}, {"stripe", "secretKey", true},
{"apiSecret", true}, {"stripe", "webhookSecret", true},
{"pkey", true}, {"stripe", "SecretKey", true}, // case-insensitive
{"privateKey", true}, {"stripe", "publishableKey", false},
{"apiPassword", true}, {"stripe", "appId", false},
{"appKey", true},
{"SECRET_TOKEN", true},
{"PrivateData", true},
{"PASSWORD", true},
{"mySecretValue", true},
// Non-sensitive fields // Alipay
{"appId", false}, {"alipay", "privateKey", true},
{"mchId", false}, {"alipay", "publicKey", true},
{"apiBase", false}, {"alipay", "alipayPublicKey", true},
{"endpoint", false}, {"alipay", "appId", false},
{"merchantNo", false}, {"alipay", "notifyUrl", false},
{"paymentMode", false},
{"notifyUrl", false}, // Wxpay
{"wxpay", "privateKey", true},
{"wxpay", "apiV3Key", true},
{"wxpay", "publicKey", true},
{"wxpay", "publicKeyId", false},
{"wxpay", "certSerial", false},
{"wxpay", "mchId", false},
// EasyPay
{"easypay", "pkey", true},
{"easypay", "pid", false},
{"easypay", "apiBase", false},
// Unknown provider: never sensitive
{"unknown", "secretKey", false},
} }
for _, tc := range tests { for _, tc := range tests {
t.Run(tc.field, func(t *testing.T) { tc := tc
t.Run(tc.providerKey+"/"+tc.field, func(t *testing.T) {
t.Parallel() t.Parallel()
got := isSensitiveConfigField(tc.field) got := isSensitiveProviderConfigField(tc.providerKey, tc.field)
assert.Equal(t, tc.wantSen, got, "isSensitiveConfigField(%q)", tc.field) assert.Equal(t, tc.wantSen, got, "isSensitiveProviderConfigField(%q, %q)", tc.providerKey, tc.field)
}) })
} }
} }

View File

@ -2,6 +2,7 @@ package service
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"log/slog" "log/slog"
"math" "math"
@ -201,7 +202,7 @@ func (s *PaymentService) checkPendingLimit(ctx context.Context, tx *dbent.Tx, us
return fmt.Errorf("count pending orders: %w", err) return fmt.Errorf("count pending orders: %w", err)
} }
if c >= max { if c >= max {
return infraerrors.TooManyRequests("TOO_MANY_PENDING", fmt.Sprintf("too many pending orders (max %d)", max)). return infraerrors.TooManyRequests("TOO_MANY_PENDING", "too_many_pending").
WithMetadata(map[string]string{"max": strconv.Itoa(max)}) WithMetadata(map[string]string{"max": strconv.Itoa(max)})
} }
return nil return nil
@ -284,7 +285,8 @@ func (s *PaymentService) checkDailyLimit(ctx context.Context, tx *dbent.Tx, user
used += o.Amount used += o.Amount
} }
if used+amount > limit { if used+amount > limit {
return infraerrors.TooManyRequests("DAILY_LIMIT_EXCEEDED", fmt.Sprintf("daily recharge limit reached, remaining: %.2f", math.Max(0, limit-used))) return infraerrors.TooManyRequests("DAILY_LIMIT_EXCEEDED", "daily_limit_exceeded").
WithMetadata(map[string]string{"remaining": fmt.Sprintf("%.2f", math.Max(0, limit-used))})
} }
return nil return nil
} }
@ -296,10 +298,11 @@ func (s *PaymentService) selectCreateOrderInstance(ctx context.Context, req Crea
} }
sel, err := s.loadBalancer.SelectInstance(selectCtx, "", req.PaymentType, payment.Strategy(cfg.LoadBalanceStrategy), payAmount) sel, err := s.loadBalancer.SelectInstance(selectCtx, "", req.PaymentType, payment.Strategy(cfg.LoadBalanceStrategy), payAmount)
if err != nil { if err != nil {
return nil, infraerrors.ServiceUnavailable("PAYMENT_GATEWAY_ERROR", fmt.Sprintf("payment method (%s) is not configured", req.PaymentType)) return nil, infraerrors.ServiceUnavailable("PAYMENT_GATEWAY_ERROR", "method_not_configured").
WithMetadata(map[string]string{"payment_type": req.PaymentType})
} }
if sel == nil { if sel == nil {
return nil, infraerrors.TooManyRequests("NO_AVAILABLE_INSTANCE", "no available payment instance") return nil, infraerrors.TooManyRequests("NO_AVAILABLE_INSTANCE", "no_available_instance")
} }
return sel, nil return sel, nil
} }
@ -342,7 +345,18 @@ func (s *PaymentService) usesOfficialWxpayVisibleMethod(ctx context.Context) boo
func (s *PaymentService) invokeProvider(ctx context.Context, order *dbent.PaymentOrder, req CreateOrderRequest, cfg *PaymentConfig, limitAmount float64, payAmountStr string, payAmount float64, plan *dbent.SubscriptionPlan, sel *payment.InstanceSelection) (*CreateOrderResponse, error) { func (s *PaymentService) invokeProvider(ctx context.Context, order *dbent.PaymentOrder, req CreateOrderRequest, cfg *PaymentConfig, limitAmount float64, payAmountStr string, payAmount float64, plan *dbent.SubscriptionPlan, sel *payment.InstanceSelection) (*CreateOrderResponse, error) {
prov, err := provider.CreateProvider(sel.ProviderKey, sel.InstanceID, sel.Config) prov, err := provider.CreateProvider(sel.ProviderKey, sel.InstanceID, sel.Config)
if err != nil { if err != nil {
return nil, infraerrors.ServiceUnavailable("PAYMENT_GATEWAY_ERROR", "payment method is temporarily unavailable") slog.Error("[PaymentService] CreateProvider failed", "provider", sel.ProviderKey, "instance", sel.InstanceID, "error", err)
// If the provider returned a structured ApplicationError (e.g. WXPAY_CONFIG_MISSING_KEY),
// pass it through with provider context added to metadata. Otherwise wrap as PAYMENT_PROVIDER_MISCONFIGURED.
if appErr := new(infraerrors.ApplicationError); errors.As(err, &appErr) {
md := map[string]string{"provider": sel.ProviderKey, "instance_id": sel.InstanceID}
for k, v := range appErr.Metadata {
md[k] = v
}
return nil, appErr.WithMetadata(md)
}
return nil, infraerrors.ServiceUnavailable("PAYMENT_PROVIDER_MISCONFIGURED", "provider_misconfigured").
WithMetadata(map[string]string{"provider": sel.ProviderKey, "instance_id": sel.InstanceID})
} }
subject := s.buildPaymentSubject(plan, limitAmount, cfg) subject := s.buildPaymentSubject(plan, limitAmount, cfg)
outTradeNo := order.OutTradeNo outTradeNo := order.OutTradeNo
@ -380,6 +394,9 @@ func (s *PaymentService) invokeProvider(ctx context.Context, order *dbent.Paymen
pr, err := prov.CreatePayment(ctx, providerReq) pr, err := prov.CreatePayment(ctx, providerReq)
if err != nil { if err != nil {
slog.Error("[PaymentService] CreatePayment failed", "provider", sel.ProviderKey, "instance", sel.InstanceID, "error", err) slog.Error("[PaymentService] CreatePayment failed", "provider", sel.ProviderKey, "instance", sel.InstanceID, "error", err)
if appErr := new(infraerrors.ApplicationError); errors.As(err, &appErr) {
return nil, appErr
}
return nil, classifyCreatePaymentError(req, sel.ProviderKey, err) return nil, classifyCreatePaymentError(req, sel.ProviderKey, err)
} }
_, err = s.entClient.PaymentOrder.UpdateOneID(order.ID). _, err = s.entClient.PaymentOrder.UpdateOneID(order.ID).

View File

@ -15,20 +15,8 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
// TestShouldClearStickySession 测试粘性会话清理判断逻辑。 // TestShouldClearStickySession tests sticky session clearing via IsSchedulable() delegation
// 验证在以下情况下是否正确判断需要清理粘性会话: // plus model-level rate limiting.
// - nil 账号:不清理(返回 false
// - 状态为错误或禁用:清理
// - 不可调度:清理
// - 临时不可调度且未过期:清理
// - 临时不可调度已过期:不清理
// - 正常可调度状态:不清理
// - 模型限流(任意时长):清理
//
// TestShouldClearStickySession tests the sticky session clearing logic.
// Verifies correct behavior for various account states including:
// nil account, error/disabled status, unschedulable, temporary unschedulable,
// and model rate limiting scenarios.
func TestShouldClearStickySession(t *testing.T) { func TestShouldClearStickySession(t *testing.T) {
now := time.Now() now := time.Now()
future := now.Add(1 * time.Hour) future := now.Add(1 * time.Hour)
@ -101,6 +89,56 @@ func TestShouldClearStickySession(t *testing.T) {
requestedModel: "claude-opus-4", // 请求不同模型 requestedModel: "claude-opus-4", // 请求不同模型
want: false, // 不同模型不受影响 want: false, // 不同模型不受影响
}, },
{
name: "apikey quota exceeded",
account: &Account{
Status: StatusActive,
Schedulable: true,
Type: AccountTypeAPIKey,
Extra: map[string]any{
"quota_daily_limit": 10.0,
"quota_daily_used": 10.0,
"quota_daily_start": now.Add(-1 * time.Hour).Format(time.RFC3339),
},
},
requestedModel: "",
want: true,
},
{
name: "oauth quota exceeded not cleared",
account: &Account{
Status: StatusActive,
Schedulable: true,
Type: AccountTypeOAuth,
Extra: map[string]any{
"quota_daily_limit": 10.0,
"quota_daily_used": 10.0,
"quota_daily_start": now.Add(-1 * time.Hour).Format(time.RFC3339),
},
},
requestedModel: "",
want: false,
},
{
name: "overloaded account",
account: &Account{
Status: StatusActive,
Schedulable: true,
OverloadUntil: &future,
},
requestedModel: "",
want: true,
},
{
name: "account-level rate limited",
account: &Account{
Status: StatusActive,
Schedulable: true,
RateLimitResetAt: &future,
},
requestedModel: "",
want: true,
},
} }
for _, tt := range tests { for _, tt := range tests {

View File

@ -12,7 +12,9 @@ import (
var ErrUpstreamResponseBodyTooLarge = errors.New("upstream response body too large") var ErrUpstreamResponseBodyTooLarge = errors.New("upstream response body too large")
const defaultUpstreamResponseReadMaxBytes int64 = 8 * 1024 * 1024 // defaultUpstreamResponseReadMaxBytes 源自 config.DefaultUpstreamResponseReadMaxBytes
// 仅在 cfg 为 nil 时作为兜底(测试或极端场景)。
const defaultUpstreamResponseReadMaxBytes = config.DefaultUpstreamResponseReadMaxBytes
func resolveUpstreamResponseReadLimit(cfg *config.Config) int64 { func resolveUpstreamResponseReadLimit(cfg *config.Config) int64 {
if cfg != nil && cfg.Gateway.UpstreamResponseReadMaxBytes > 0 { if cfg != nil && cfg.Gateway.UpstreamResponseReadMaxBytes > 0 {

View File

@ -284,6 +284,16 @@ const hasError = computed(() => {
return props.account.status === 'error' return props.account.status === 'error'
}) })
const isQuotaExceeded = computed(() => {
const exceeded = (used?: number | null, limit?: number | null) =>
typeof limit === 'number' && limit > 0 && typeof used === 'number' && used >= limit
return (
exceeded(props.account.quota_used, props.account.quota_limit) ||
exceeded(props.account.quota_daily_used, props.account.quota_daily_limit) ||
exceeded(props.account.quota_weekly_used, props.account.quota_weekly_limit)
)
})
// Computed: countdown text for rate limit (429) // Computed: countdown text for rate limit (429)
const rateLimitCountdown = computed(() => { const rateLimitCountdown = computed(() => {
return formatCountdown(props.account.rate_limit_reset_at) return formatCountdown(props.account.rate_limit_reset_at)
@ -307,19 +317,16 @@ const statusClass = computed(() => {
if (isTempUnschedulable.value) { if (isTempUnschedulable.value) {
return 'badge-warning' return 'badge-warning'
} }
if (props.account.status !== 'active') {
return props.account.status === 'error' ? 'badge-danger' : 'badge-gray'
}
if (isQuotaExceeded.value) {
return 'badge-warning'
}
if (!props.account.schedulable) { if (!props.account.schedulable) {
return 'badge-gray' return 'badge-gray'
} }
switch (props.account.status) { return 'badge-success'
case 'active':
return 'badge-success'
case 'inactive':
return 'badge-gray'
case 'error':
return 'badge-danger'
default:
return 'badge-gray'
}
}) })
// Computed: status text // Computed: status text
@ -330,6 +337,12 @@ const statusText = computed(() => {
if (isTempUnschedulable.value) { if (isTempUnschedulable.value) {
return t('admin.accounts.status.tempUnschedulable') return t('admin.accounts.status.tempUnschedulable')
} }
if (props.account.status !== 'active') {
return t(`admin.accounts.status.${props.account.status}`)
}
if (isQuotaExceeded.value) {
return t('admin.accounts.status.quotaExceeded')
}
if (!props.account.schedulable) { if (!props.account.schedulable) {
return t('admin.accounts.status.paused') return t('admin.accounts.status.paused')
} }

View File

@ -52,6 +52,10 @@
v-model="editApiKey" v-model="editApiKey"
type="password" type="password"
class="input font-mono" class="input font-mono"
autocomplete="new-password"
data-1p-ignore
data-lpignore="true"
data-bwignore="true"
:placeholder=" :placeholder="
account.platform === 'openai' account.platform === 'openai'
? 'sk-proj-...' ? 'sk-proj-...'

View File

@ -166,7 +166,7 @@
<input <input
type="number" type="number"
step="0.001" step="0.001"
min="0" min="0.001"
autocomplete="off" autocomplete="off"
:value="entry.rate_multiplier" :value="entry.rate_multiplier"
class="hide-spinner w-20 rounded border border-gray-200 bg-white px-2 py-1 text-center text-sm font-medium transition-colors focus:border-primary-500 focus:outline-none focus:ring-1 focus:ring-primary-500/20 dark:border-dark-500 dark:bg-dark-700 dark:focus:border-primary-500" class="hide-spinner w-20 rounded border border-gray-200 bg-white px-2 py-1 text-center text-sm font-medium transition-colors focus:border-primary-500 focus:outline-none focus:ring-1 focus:ring-primary-500/20 dark:border-dark-500 dark:bg-dark-700 dark:focus:border-primary-500"

View File

@ -81,7 +81,7 @@
<input <input
type="number" type="number"
step="0.001" step="0.001"
min="0" min="0.001"
:value="config.customRate ?? ''" :value="config.customRate ?? ''"
@input="updateCustomRate(config.groupId, ($event.target as HTMLInputElement).value)" @input="updateCustomRate(config.groupId, ($event.target as HTMLInputElement).value)"
:placeholder="String(config.defaultRate)" :placeholder="String(config.defaultRate)"
@ -139,7 +139,7 @@
<input <input
type="number" type="number"
step="0.001" step="0.001"
min="0" min="0.001"
:value="config.customRate ?? ''" :value="config.customRate ?? ''"
@input="updateCustomRate(config.groupId, ($event.target as HTMLInputElement).value)" @input="updateCustomRate(config.groupId, ($event.target as HTMLInputElement).value)"
:placeholder="String(config.defaultRate)" :placeholder="String(config.defaultRate)"

View File

@ -617,66 +617,6 @@ function generateOpenCodeConfig(platform: string, baseUrl: string, apiKey: strin
} }
} }
const openaiModels = { const openaiModels = {
'gpt-5-codex': {
name: 'GPT-5 Codex',
limit: {
context: 400000,
output: 128000
},
options: {
store: false
},
variants: {
low: {},
medium: {},
high: {}
}
},
'gpt-5.1-codex': {
name: 'GPT-5.1 Codex',
limit: {
context: 400000,
output: 128000
},
options: {
store: false
},
variants: {
low: {},
medium: {},
high: {}
}
},
'gpt-5.1-codex-max': {
name: 'GPT-5.1 Codex Max',
limit: {
context: 400000,
output: 128000
},
options: {
store: false
},
variants: {
low: {},
medium: {},
high: {}
}
},
'gpt-5.1-codex-mini': {
name: 'GPT-5.1 Codex Mini',
limit: {
context: 400000,
output: 128000
},
options: {
store: false
},
variants: {
low: {},
medium: {},
high: {}
}
},
'gpt-5.2': { 'gpt-5.2': {
name: 'GPT-5.2', name: 'GPT-5.2',
limit: { limit: {
@ -725,22 +665,6 @@ function generateOpenCodeConfig(platform: string, baseUrl: string, apiKey: strin
xhigh: {} xhigh: {}
} }
}, },
'gpt-5.4-nano': {
name: 'GPT-5.4 Nano',
limit: {
context: 400000,
output: 128000
},
options: {
store: false
},
variants: {
low: {},
medium: {},
high: {},
xhigh: {}
}
},
'gpt-5.3-codex-spark': { 'gpt-5.3-codex-spark': {
name: 'GPT-5.3 Codex Spark', name: 'GPT-5.3 Codex Spark',
limit: { limit: {
@ -773,22 +697,6 @@ function generateOpenCodeConfig(platform: string, baseUrl: string, apiKey: strin
xhigh: {} xhigh: {}
} }
}, },
'gpt-5.2-codex': {
name: 'GPT-5.2 Codex',
limit: {
context: 400000,
output: 128000
},
options: {
store: false
},
variants: {
low: {},
medium: {},
high: {},
xhigh: {}
}
},
'codex-mini-latest': { 'codex-mini-latest': {
name: 'Codex Mini', name: 'Codex Mini',
limit: { limit: {

View File

@ -17,7 +17,7 @@ vi.mock('@/composables/useClipboard', () => ({
import UseKeyModal from '../UseKeyModal.vue' import UseKeyModal from '../UseKeyModal.vue'
describe('UseKeyModal', () => { describe('UseKeyModal', () => {
it('renders updated GPT-5.4 mini/nano names in OpenCode config', async () => { it('renders GPT-5.4 mini entry in OpenCode config', async () => {
const wrapper = mount(UseKeyModal, { const wrapper = mount(UseKeyModal, {
props: { props: {
show: true, show: true,
@ -48,6 +48,6 @@ describe('UseKeyModal', () => {
const codeBlock = wrapper.find('pre code') const codeBlock = wrapper.find('pre code')
expect(codeBlock.exists()).toBe(true) expect(codeBlock.exists()).toBe(true)
expect(codeBlock.text()).toContain('"name": "GPT-5.4 Mini"') expect(codeBlock.text()).toContain('"name": "GPT-5.4 Mini"')
expect(codeBlock.text()).toContain('"name": "GPT-5.4 Nano"') expect(codeBlock.text()).not.toContain('"name": "GPT-5.4 Nano"')
}) })
}) })

View File

@ -88,13 +88,24 @@
v-model="config[field.key]" v-model="config[field.key]"
rows="3" rows="3"
class="input font-mono text-xs" class="input font-mono text-xs"
autocomplete="new-password"
data-1p-ignore
data-lpignore="true"
data-bwignore="true"
spellcheck="false"
:placeholder="editing ? t('admin.accounts.leaveEmptyToKeep') : ''"
/> />
<div v-else-if="field.sensitive" class="relative"> <div v-else-if="field.sensitive" class="relative">
<input <input
:type="visibleFields[field.key] ? 'text' : 'password'" :type="visibleFields[field.key] ? 'text' : 'password'"
v-model="config[field.key]" v-model="config[field.key]"
class="input pr-10" class="input pr-10"
:placeholder="field.defaultValue || ''" autocomplete="new-password"
data-1p-ignore
data-lpignore="true"
data-bwignore="true"
spellcheck="false"
:placeholder="editing ? t('admin.accounts.leaveEmptyToKeep') : (field.defaultValue || '')"
/> />
<button <button
type="button" type="button"
@ -398,9 +409,12 @@ function handleSave() {
emitValidationError(t('admin.settings.payment.validationNameRequired')) emitValidationError(t('admin.settings.payment.validationNameRequired'))
return return
} }
// Validate required config fields all non-optional fields must be filled // Validate required config fields all non-optional fields must be filled.
// In edit mode, sensitive fields may be left blank to preserve the stored
// value (backend merges blanks by preserving the existing secret).
for (const f of PROVIDER_CONFIG_FIELDS[form.provider_key] || []) { for (const f of PROVIDER_CONFIG_FIELDS[form.provider_key] || []) {
if (f.optional) continue if (f.optional) continue
if (props.editing && f.sensitive) continue
const val = (config[f.key] || '').trim() const val = (config[f.key] || '').trim()
if (!val) { if (!val) {
const label = f.label || t(`admin.settings.payment.field_${f.key}`) const label = f.label || t(`admin.settings.payment.field_${f.key}`)
@ -412,8 +426,6 @@ function handleSave() {
const filteredConfig: Record<string, string> = {} const filteredConfig: Record<string, string> = {}
for (const [k, v] of Object.entries(config)) { for (const [k, v] of Object.entries(config)) {
if (!v || !v.trim()) continue if (!v || !v.trim()) continue
// Skip masked values backend keeps existing credentials
if (v === '••••••••') continue
filteredConfig[k] = v filteredConfig[k] = v
} }
@ -470,7 +482,8 @@ function loadProvider(provider: ProviderInstance) {
form.refund_enabled = provider.refund_enabled form.refund_enabled = provider.refund_enabled
form.allow_user_refund = provider.allow_user_refund form.allow_user_refund = provider.allow_user_refund
clearConfig() clearConfig()
// Pre-fill config from API response (non-sensitive in cleartext, sensitive masked as ) // Pre-fill config from API response. Backend omits sensitive fields entirely,
// so those inputs stay blank submitting blank preserves the stored secret.
if (provider.config) { if (provider.config) {
for (const [k, v] of Object.entries(provider.config)) { for (const [k, v] of Object.entries(provider.config)) {
// Skip notifyUrl/returnUrl they are derived from callbackBaseUrl // Skip notifyUrl/returnUrl they are derived from callbackBaseUrl

View File

@ -78,8 +78,8 @@ import Icon from '@/components/icons/Icon.vue'
import { usePaymentStore } from '@/stores/payment' import { usePaymentStore } from '@/stores/payment'
import { useAppStore } from '@/stores' import { useAppStore } from '@/stores'
import { paymentAPI } from '@/api/payment' import { paymentAPI } from '@/api/payment'
import { extractApiErrorMessage } from '@/utils/apiError' import { extractI18nErrorMessage } from '@/utils/apiError'
import { POPUP_WINDOW_FEATURES } from '@/components/payment/providerConfig' import { getPaymentPopupFeatures } from '@/components/payment/providerConfig'
import type { PaymentOrder } from '@/types/payment' import type { PaymentOrder } from '@/types/payment'
import QRCode from 'qrcode' import QRCode from 'qrcode'
import alipayIcon from '@/assets/icons/alipay.svg' import alipayIcon from '@/assets/icons/alipay.svg'
@ -147,7 +147,7 @@ function getLogoForType(): string | null {
function reopenPopup() { function reopenPopup() {
if (props.payUrl) { if (props.payUrl) {
window.open(props.payUrl, 'paymentPopup', POPUP_WINDOW_FEATURES) window.open(props.payUrl, 'paymentPopup', getPaymentPopupFeatures())
} }
} }
@ -222,7 +222,7 @@ async function handleCancel() {
cleanup() cleanup()
emit('close') emit('close')
} catch (err: unknown) { } catch (err: unknown) {
appStore.showError(extractApiErrorMessage(err, t('common.error'))) appStore.showError(extractI18nErrorMessage(err, t, 'payment.errors', t('common.error')))
} finally { } finally {
cancelling.value = false cancelling.value = false
} }

View File

@ -124,8 +124,8 @@ import { useI18n } from 'vue-i18n'
import { usePaymentStore } from '@/stores/payment' import { usePaymentStore } from '@/stores/payment'
import { useAppStore } from '@/stores' import { useAppStore } from '@/stores'
import { paymentAPI } from '@/api/payment' import { paymentAPI } from '@/api/payment'
import { extractApiErrorMessage } from '@/utils/apiError' import { extractI18nErrorMessage } from '@/utils/apiError'
import { POPUP_WINDOW_FEATURES } from '@/components/payment/providerConfig' import { getPaymentPopupFeatures } from '@/components/payment/providerConfig'
import type { PaymentOrder } from '@/types/payment' import type { PaymentOrder } from '@/types/payment'
import Icon from '@/components/icons/Icon.vue' import Icon from '@/components/icons/Icon.vue'
import QRCode from 'qrcode' import QRCode from 'qrcode'
@ -200,7 +200,7 @@ function isSuccessStatus(status: string | null | undefined): boolean {
function reopenPopup() { function reopenPopup() {
if (props.payUrl) { if (props.payUrl) {
const win = window.open(props.payUrl, 'paymentPopup', POPUP_WINDOW_FEATURES) const win = window.open(props.payUrl, 'paymentPopup', getPaymentPopupFeatures())
if (!win || win.closed) { if (!win || win.closed) {
window.location.href = props.payUrl window.location.href = props.payUrl
} }
@ -257,7 +257,7 @@ async function handleCancel() {
cleanup() cleanup()
setOutcome('cancelled') setOutcome('cancelled')
} catch (err: unknown) { } catch (err: unknown) {
appStore.showError(extractApiErrorMessage(err, t('common.error'))) appStore.showError(extractI18nErrorMessage(err, t, 'payment.errors', t('common.error')))
} finally { } finally {
cancelling.value = false cancelling.value = false
} }

View File

@ -67,10 +67,10 @@
import { ref, onMounted, nextTick } from 'vue' import { ref, onMounted, nextTick } from 'vue'
import { useI18n } from 'vue-i18n' import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router' import { useRouter } from 'vue-router'
import { extractApiErrorMessage } from '@/utils/apiError' import { extractI18nErrorMessage } from '@/utils/apiError'
import { paymentAPI } from '@/api/payment' import { paymentAPI } from '@/api/payment'
import { useAppStore } from '@/stores' import { useAppStore } from '@/stores'
import { STRIPE_POPUP_WINDOW_FEATURES } from '@/components/payment/providerConfig' import { getPaymentPopupFeatures } from '@/components/payment/providerConfig'
import type { Stripe, StripeElements } from '@stripe/stripe-js' import type { Stripe, StripeElements } from '@stripe/stripe-js'
import Icon from '@/components/icons/Icon.vue' import Icon from '@/components/icons/Icon.vue'
@ -132,7 +132,7 @@ onMounted(async () => {
selectedType.value = event.value.type selectedType.value = event.value.type
}) })
} catch (err: unknown) { } catch (err: unknown) {
initError.value = extractApiErrorMessage(err, t('payment.stripeLoadFailed')) initError.value = extractI18nErrorMessage(err, t, 'payment.errors', t('payment.stripeLoadFailed'))
} finally { } finally {
loading.value = false loading.value = false
} }
@ -151,7 +151,7 @@ async function handlePay() {
amount: String(props.payAmount), amount: String(props.payAmount),
}, },
}).href }).href
const popup = window.open(popupUrl, 'paymentPopup', STRIPE_POPUP_WINDOW_FEATURES) const popup = window.open(popupUrl, 'paymentPopup', getPaymentPopupFeatures())
const onReady = (event: MessageEvent) => { const onReady = (event: MessageEvent) => {
if (event.source !== popup || event.data?.type !== 'STRIPE_POPUP_READY') return if (event.source !== popup || event.data?.type !== 'STRIPE_POPUP_READY') return
@ -186,7 +186,7 @@ async function handlePay() {
emit('success') emit('success')
} }
} catch (err: unknown) { } catch (err: unknown) {
error.value = extractApiErrorMessage(err, t('payment.result.failed')) error.value = extractI18nErrorMessage(err, t, 'payment.errors', t('payment.result.failed'))
} finally { } finally {
submitting.value = false submitting.value = false
} }
@ -199,7 +199,7 @@ async function handleCancel() {
await paymentAPI.cancelOrder(props.orderId) await paymentAPI.cancelOrder(props.orderId)
emit('back') emit('back')
} catch (err: unknown) { } catch (err: unknown) {
appStore.showError(extractApiErrorMessage(err, t('common.error'))) appStore.showError(extractI18nErrorMessage(err, t, 'payment.errors', t('common.error')))
} finally { } finally {
cancelling.value = false cancelling.value = false
} }

View File

@ -43,11 +43,24 @@ export const METHOD_ORDER = ['alipay', 'alipay_direct', 'wxpay', 'wxpay_direct',
export const PAYMENT_MODE_QRCODE = 'qrcode' export const PAYMENT_MODE_QRCODE = 'qrcode'
export const PAYMENT_MODE_POPUP = 'popup' export const PAYMENT_MODE_POPUP = 'popup'
/** Window features for payment popup windows */ /** Preferred popup size for payment gateways. Alipay's standard checkout
export const POPUP_WINDOW_FEATURES = 'width=1000,height=750,left=100,top=80,scrollbars=yes,resizable=yes' * (QR + account login panel) needs ~1200×900 to render without any scrolling. */
const PAYMENT_POPUP_PREFERRED_WIDTH = 1250
const PAYMENT_POPUP_PREFERRED_HEIGHT = 900
/** Wider popup for Stripe redirect methods (Alipay checkout page needs ~1200px) */ /** Build a window.open features string sized to fit within the current screen
export const STRIPE_POPUP_WINDOW_FEATURES = 'width=1250,height=780,left=80,top=60,scrollbars=yes,resizable=yes' * while preferring the above dimensions. Centers the popup on the available
* work area so nothing is clipped on smaller laptop displays. */
export function getPaymentPopupFeatures(): string {
const screen = typeof window !== 'undefined' ? window.screen : null
const availW = screen?.availWidth ?? PAYMENT_POPUP_PREFERRED_WIDTH
const availH = screen?.availHeight ?? PAYMENT_POPUP_PREFERRED_HEIGHT
const width = Math.min(PAYMENT_POPUP_PREFERRED_WIDTH, availW - 40)
const height = Math.min(PAYMENT_POPUP_PREFERRED_HEIGHT, availH - 40)
const left = Math.max(0, Math.floor((availW - width) / 2))
const top = Math.max(0, Math.floor((availH - height) / 2))
return `width=${width},height=${height},left=${left},top=${top},scrollbars=yes,resizable=yes`
}
/** Webhook paths for each provider (relative to origin). */ /** Webhook paths for each provider (relative to origin). */
export const WEBHOOK_PATHS: Record<string, string> = { export const WEBHOOK_PATHS: Record<string, string> = {
@ -87,9 +100,9 @@ export const PROVIDER_CONFIG_FIELDS: Record<string, ConfigFieldDef[]> = {
{ key: 'mchId', label: '', sensitive: false }, { key: 'mchId', label: '', sensitive: false },
{ key: 'privateKey', label: '', sensitive: true }, { key: 'privateKey', label: '', sensitive: true },
{ key: 'apiV3Key', label: '', sensitive: true }, { key: 'apiV3Key', label: '', sensitive: true },
{ key: 'certSerial', label: '', sensitive: false },
{ key: 'publicKey', label: '', sensitive: true }, { key: 'publicKey', label: '', sensitive: true },
{ key: 'publicKeyId', label: '', sensitive: false }, { key: 'publicKeyId', label: '', sensitive: false },
{ key: 'certSerial', label: '', sensitive: false },
{ key: 'h5AppName', label: '', sensitive: false, optional: true }, { key: 'h5AppName', label: '', sensitive: false, optional: true },
{ key: 'h5AppUrl', label: '', sensitive: false, optional: true }, { key: 'h5AppUrl', label: '', sensitive: false, optional: true },
], ],

View File

@ -12,10 +12,20 @@ describe('useModelWhitelist', () => {
expect(models).toContain('gpt-5.4') expect(models).toContain('gpt-5.4')
expect(models).toContain('gpt-5.4-mini') expect(models).toContain('gpt-5.4-mini')
expect(models).toContain('gpt-5.4-nano')
expect(models).toContain('gpt-5.4-2026-03-05') expect(models).toContain('gpt-5.4-2026-03-05')
}) })
it('openai 模型列表不再暴露已下线的 ChatGPT 登录 Codex 模型', () => {
const models = getModelsByPlatform('openai')
expect(models).not.toContain('gpt-5')
expect(models).not.toContain('gpt-5.1')
expect(models).not.toContain('gpt-5.1-codex')
expect(models).not.toContain('gpt-5.1-codex-max')
expect(models).not.toContain('gpt-5.1-codex-mini')
expect(models).not.toContain('gpt-5.2-codex')
})
it('antigravity 模型列表包含图片模型兼容项', () => { it('antigravity 模型列表包含图片模型兼容项', () => {
const models = getModelsByPlatform('antigravity') const models = getModelsByPlatform('antigravity')
@ -55,12 +65,11 @@ describe('useModelWhitelist', () => {
}) })
}) })
it('whitelist keeps GPT-5.4 mini and nano exact mappings', () => { it('whitelist keeps GPT-5.4 mini exact mappings', () => {
const mapping = buildModelMappingObject('whitelist', ['gpt-5.4-mini', 'gpt-5.4-nano'], []) const mapping = buildModelMappingObject('whitelist', ['gpt-5.4-mini'], [])
expect(mapping).toEqual({ expect(mapping).toEqual({
'gpt-5.4-mini': 'gpt-5.4-mini', 'gpt-5.4-mini': 'gpt-5.4-mini'
'gpt-5.4-nano': 'gpt-5.4-nano'
}) })
}) })
}) })

View File

@ -13,19 +13,11 @@ const openaiModels = [
'o1', 'o1-preview', 'o1-mini', 'o1-pro', 'o1', 'o1-preview', 'o1-mini', 'o1-pro',
'o3', 'o3-mini', 'o3-pro', 'o3', 'o3-mini', 'o3-pro',
'o4-mini', 'o4-mini',
// GPT-5 系列(同步后端定价文件)
'gpt-5', 'gpt-5-2025-08-07', 'gpt-5-chat', 'gpt-5-chat-latest',
'gpt-5-codex', 'gpt-5.3-codex-spark', 'gpt-5-pro', 'gpt-5-pro-2025-10-06',
'gpt-5-mini', 'gpt-5-mini-2025-08-07',
'gpt-5-nano', 'gpt-5-nano-2025-08-07',
// GPT-5.1 系列
'gpt-5.1', 'gpt-5.1-2025-11-13', 'gpt-5.1-chat-latest',
'gpt-5.1-codex', 'gpt-5.1-codex-max', 'gpt-5.1-codex-mini',
// GPT-5.2 系列 // GPT-5.2 系列
'gpt-5.2', 'gpt-5.2-2025-12-11', 'gpt-5.2-chat-latest', 'gpt-5.2', 'gpt-5.2-2025-12-11', 'gpt-5.2-chat-latest',
'gpt-5.2-codex', 'gpt-5.2-pro', 'gpt-5.2-pro-2025-12-11', 'gpt-5.2-pro', 'gpt-5.2-pro-2025-12-11',
// GPT-5.4 系列 // GPT-5.4 系列
'gpt-5.4', 'gpt-5.4-mini', 'gpt-5.4-nano', 'gpt-5.4-2026-03-05', 'gpt-5.4', 'gpt-5.4-mini', 'gpt-5.4-2026-03-05',
// GPT-5.3 系列 // GPT-5.3 系列
'gpt-5.3-codex', 'gpt-5.3-codex-spark', 'gpt-5.3-codex', 'gpt-5.3-codex-spark',
'chatgpt-4o-latest', 'chatgpt-4o-latest',
@ -264,12 +256,9 @@ const openaiPresetMappings = [
{ label: 'GPT-4.1', from: 'gpt-4.1', to: 'gpt-4.1', color: 'bg-indigo-100 text-indigo-700 hover:bg-indigo-200 dark:bg-indigo-900/30 dark:text-indigo-400' }, { label: 'GPT-4.1', from: 'gpt-4.1', to: 'gpt-4.1', color: 'bg-indigo-100 text-indigo-700 hover:bg-indigo-200 dark:bg-indigo-900/30 dark:text-indigo-400' },
{ label: 'o1', from: 'o1', to: 'o1', color: 'bg-purple-100 text-purple-700 hover:bg-purple-200 dark:bg-purple-900/30 dark:text-purple-400' }, { label: 'o1', from: 'o1', to: 'o1', color: 'bg-purple-100 text-purple-700 hover:bg-purple-200 dark:bg-purple-900/30 dark:text-purple-400' },
{ label: 'o3', from: 'o3', to: 'o3', color: 'bg-emerald-100 text-emerald-700 hover:bg-emerald-200 dark:bg-emerald-900/30 dark:text-emerald-400' }, { label: 'o3', from: 'o3', to: 'o3', color: 'bg-emerald-100 text-emerald-700 hover:bg-emerald-200 dark:bg-emerald-900/30 dark:text-emerald-400' },
{ label: 'GPT-5', from: 'gpt-5', to: 'gpt-5', color: 'bg-amber-100 text-amber-700 hover:bg-amber-200 dark:bg-amber-900/30 dark:text-amber-400' },
{ label: 'GPT-5.3 Codex Spark', from: 'gpt-5.3-codex-spark', to: 'gpt-5.3-codex-spark', color: 'bg-teal-100 text-teal-700 hover:bg-teal-200 dark:bg-teal-900/30 dark:text-teal-400' }, { label: 'GPT-5.3 Codex Spark', from: 'gpt-5.3-codex-spark', to: 'gpt-5.3-codex-spark', color: 'bg-teal-100 text-teal-700 hover:bg-teal-200 dark:bg-teal-900/30 dark:text-teal-400' },
{ label: 'GPT-5.1', from: 'gpt-5.1', to: 'gpt-5.1', color: 'bg-orange-100 text-orange-700 hover:bg-orange-200 dark:bg-orange-900/30 dark:text-orange-400' },
{ label: 'GPT-5.2', from: 'gpt-5.2', to: 'gpt-5.2', color: 'bg-red-100 text-red-700 hover:bg-red-200 dark:bg-red-900/30 dark:text-red-400' }, { label: 'GPT-5.2', from: 'gpt-5.2', to: 'gpt-5.2', color: 'bg-red-100 text-red-700 hover:bg-red-200 dark:bg-red-900/30 dark:text-red-400' },
{ label: 'GPT-5.4', from: 'gpt-5.4', to: 'gpt-5.4', color: 'bg-rose-100 text-rose-700 hover:bg-rose-200 dark:bg-rose-900/30 dark:text-rose-400' }, { label: 'GPT-5.4', from: 'gpt-5.4', to: 'gpt-5.4', color: 'bg-rose-100 text-rose-700 hover:bg-rose-200 dark:bg-rose-900/30 dark:text-rose-400' },
{ label: 'GPT-5.1 Codex', from: 'gpt-5.1-codex', to: 'gpt-5.1-codex', color: 'bg-cyan-100 text-cyan-700 hover:bg-cyan-200 dark:bg-cyan-900/30 dark:text-cyan-400' },
{ label: 'Haiku→5.4', from: 'claude-haiku-4-5-20251001', to: 'gpt-5.4', color: 'bg-emerald-100 text-emerald-700 hover:bg-emerald-200 dark:bg-emerald-900/30 dark:text-emerald-400' }, { label: 'Haiku→5.4', from: 'claude-haiku-4-5-20251001', to: 'gpt-5.4', color: 'bg-emerald-100 text-emerald-700 hover:bg-emerald-200 dark:bg-emerald-900/30 dark:text-emerald-400' },
{ label: 'Opus→5.4', from: 'claude-opus-4-6', to: 'gpt-5.4', color: 'bg-purple-100 text-purple-700 hover:bg-purple-200 dark:bg-purple-900/30 dark:text-purple-400' }, { label: 'Opus→5.4', from: 'claude-opus-4-6', to: 'gpt-5.4', color: 'bg-purple-100 text-purple-700 hover:bg-purple-200 dark:bg-purple-900/30 dark:text-purple-400' },
{ label: 'Sonnet→5.4', from: 'claude-sonnet-4-6', to: 'gpt-5.4', color: 'bg-blue-100 text-blue-700 hover:bg-blue-200 dark:bg-blue-900/30 dark:text-blue-400' } { label: 'Sonnet→5.4', from: 'claude-sonnet-4-6', to: 'gpt-5.4', color: 'bg-blue-100 text-blue-700 hover:bg-blue-200 dark:bg-blue-900/30 dark:text-blue-400' }

View File

@ -895,6 +895,14 @@ export default {
accountBalance: 'Account Balance', accountBalance: 'Account Balance',
concurrencyLimit: 'Concurrency Limit', concurrencyLimit: 'Concurrency Limit',
memberSince: 'Member Since', memberSince: 'Member Since',
overviewTitle: 'Account Overview',
overviewDescription: 'Check account status, profile sources, and common actions at a glance.',
basicsTitle: 'Profile & Avatar',
basicsDescription: 'Keep your public profile details and avatar aligned.',
linkedProfileSources: 'Profile Sources',
linkedProfileSourcesDescription: 'Some profile details may stay synced from third-party sign-in methods.',
securityTitle: 'Security Settings',
securityDescription: 'Password, two-factor authentication, and alerts live in the right rail.',
administrator: 'Administrator', administrator: 'Administrator',
user: 'User', user: 'User',
username: 'Username', username: 'Username',
@ -1015,10 +1023,15 @@ export default {
passwordPlaceholder: 'Set a login password', passwordPlaceholder: 'Set a login password',
replaceEmailPasswordPlaceholder: 'Enter current password', replaceEmailPasswordPlaceholder: 'Enter current password',
sendCodeAction: 'Send code', sendCodeAction: 'Send code',
manageEmailAction: 'Manage email',
hideEmailFormAction: 'Hide email form',
confirmEmailBindAction: 'Bind email', confirmEmailBindAction: 'Bind email',
confirmEmailReplaceAction: 'Replace primary email', confirmEmailReplaceAction: 'Replace primary email',
codeSentTo: 'Code sent to {email}', codeSentTo: 'Code sent to {email}',
replaceSuccess: 'Primary email updated', replaceSuccess: 'Primary email updated',
unbindAction: 'Unbind',
unbindSuccess: '{providerName} unbound',
boundCount: '{count} linked records',
status: { status: {
bound: 'Bound', bound: 'Bound',
notBound: 'Not bound', notBound: 'Not bound',
@ -2222,6 +2235,7 @@ export default {
rateLimited: 'Rate Limited', rateLimited: 'Rate Limited',
overloaded: 'Overloaded', overloaded: 'Overloaded',
tempUnschedulable: 'Temp Unschedulable', tempUnschedulable: 'Temp Unschedulable',
quotaExceeded: 'Quota Exceeded',
unschedulable: 'Unschedulable', unschedulable: 'Unschedulable',
rateLimitedUntil: 'Rate limited and removed from scheduling. Auto resumes at {time}', rateLimitedUntil: 'Rate limited and removed from scheduling. Auto resumes at {time}',
rateLimitedAutoResume: 'Auto resumes in {time}', rateLimitedAutoResume: 'Auto resumes in {time}',
@ -5612,8 +5626,34 @@ export default {
alipayDesktopQrHint: 'Desktop Alipay should render a QR code. Refresh and retry, or make sure the payment page was not blocked.', alipayDesktopQrHint: 'Desktop Alipay should render a QR code. Refresh and retry, or make sure the payment page was not blocked.',
alipayMobileUnavailable: 'This page could not hand off to Alipay.', alipayMobileUnavailable: 'This page could not hand off to Alipay.',
alipayMobileOpenHint: 'Allow the current page to open the Alipay app, or retry from the system browser.', alipayMobileOpenHint: 'Allow the current page to open the Alipay app, or retry from the system browser.',
// Structured error codes (reason strings from backend ApplicationError)
PAYMENT_DISABLED: 'Payment system is disabled.',
USER_INACTIVE: 'Your account is disabled.',
BALANCE_PAYMENT_DISABLED: 'Balance recharge has been disabled.',
INVALID_AMOUNT: 'Invalid amount.',
INVALID_INPUT: 'Invalid request.',
PLAN_NOT_AVAILABLE: 'Plan not found or no longer available.',
GROUP_NOT_FOUND: 'Subscription group is no longer available.',
GROUP_TYPE_MISMATCH: 'Group is not a subscription type.',
TOO_MANY_PENDING: 'Too many pending orders (max {max}). Please complete or cancel existing orders first.',
DAILY_LIMIT_EXCEEDED: 'Daily recharge limit reached. Remaining: {remaining}.',
PAYMENT_GATEWAY_ERROR: 'Payment method is unavailable.',
NO_AVAILABLE_INSTANCE: 'No payment channel available right now.',
PAYMENT_PROVIDER_MISCONFIGURED: 'Payment provider misconfigured. Please contact an administrator.',
WXPAY_CONFIG_MISSING_KEY: 'WeChat Pay config missing required key: {key}.',
WXPAY_CONFIG_INVALID_KEY_LENGTH: 'WeChat Pay {key} length is invalid (expected {expected} bytes, got {actual}).',
WXPAY_CONFIG_INVALID_KEY: 'WeChat Pay {key} is malformed. Make sure you copied the full PEM content.',
PENDING_ORDERS: 'This provider has pending orders. Please wait for them to complete before making changes.', PENDING_ORDERS: 'This provider has pending orders. Please wait for them to complete before making changes.',
PAYMENT_PROVIDER_CONFLICT: 'Another enabled provider instance is already serving this payment method. Disable it before continuing.', PAYMENT_PROVIDER_CONFLICT: 'Another enabled provider instance is already serving this payment method. Disable it before continuing.',
CANCEL_RATE_LIMITED: 'Too many cancellations. Please try again later.',
NOT_FOUND: 'Order not found.',
FORBIDDEN: 'No permission for this order.',
CONFLICT: 'Order status has changed. Please refresh.',
INVALID_ORDER_TYPE: 'Only balance orders can request a refund.',
INVALID_STATUS: 'The current order status does not allow this operation.',
BALANCE_NOT_ENOUGH: 'Refund amount exceeds balance.',
REFUND_AMOUNT_EXCEEDED: 'Refund amount exceeds the recharge amount.',
REFUND_FAILED: 'Refund failed.',
}, },
stripePay: 'Pay Now', stripePay: 'Pay Now',
stripeSuccessProcessing: 'Payment successful, processing your order...', stripeSuccessProcessing: 'Payment successful, processing your order...',

View File

@ -899,6 +899,14 @@ export default {
accountBalance: '账户余额', accountBalance: '账户余额',
concurrencyLimit: '并发限制', concurrencyLimit: '并发限制',
memberSince: '注册时间', memberSince: '注册时间',
overviewTitle: '账户总览',
overviewDescription: '快速查看账号状态、资料来源与常用设置。',
basicsTitle: '资料与头像',
basicsDescription: '维护公开展示信息,并保持头像与昵称风格一致。',
linkedProfileSources: '资料来源',
linkedProfileSourcesDescription: '部分头像和昵称可能同步自第三方登录方式。',
securityTitle: '安全设置',
securityDescription: '密码、双因素认证和通知提醒集中放在右侧。',
administrator: '管理员', administrator: '管理员',
user: '用户', user: '用户',
username: '用户名', username: '用户名',
@ -1019,10 +1027,15 @@ export default {
passwordPlaceholder: '设置登录密码', passwordPlaceholder: '设置登录密码',
replaceEmailPasswordPlaceholder: '输入当前密码', replaceEmailPasswordPlaceholder: '输入当前密码',
sendCodeAction: '发送验证码', sendCodeAction: '发送验证码',
manageEmailAction: '管理邮箱',
hideEmailFormAction: '收起邮箱表单',
confirmEmailBindAction: '绑定邮箱', confirmEmailBindAction: '绑定邮箱',
confirmEmailReplaceAction: '更换主邮箱', confirmEmailReplaceAction: '更换主邮箱',
codeSentTo: '验证码已发送到 {email}', codeSentTo: '验证码已发送到 {email}',
replaceSuccess: '主邮箱已更新', replaceSuccess: '主邮箱已更新',
unbindAction: '解绑',
unbindSuccess: '{providerName} 已解绑',
boundCount: '已关联 {count} 条记录',
status: { status: {
bound: '已绑定', bound: '已绑定',
notBound: '未绑定', notBound: '未绑定',
@ -2411,6 +2424,7 @@ export default {
rateLimited: '限流中', rateLimited: '限流中',
overloaded: '过载中', overloaded: '过载中',
tempUnschedulable: '临时不可调度', tempUnschedulable: '临时不可调度',
quotaExceeded: '配额超限',
unschedulable: '不可调度', unschedulable: '不可调度',
rateLimitedUntil: '限流中,当前不参与调度,预计 {time} 自动恢复', rateLimitedUntil: '限流中,当前不参与调度,预计 {time} 自动恢复',
rateLimitedAutoResume: '{time} 自动恢复', rateLimitedAutoResume: '{time} 自动恢复',
@ -5800,8 +5814,34 @@ export default {
alipayDesktopQrHint: '电脑端支付宝应展示扫码单,请刷新后重试,或确认浏览器未拦截当前支付页。', alipayDesktopQrHint: '电脑端支付宝应展示扫码单,请刷新后重试,或确认浏览器未拦截当前支付页。',
alipayMobileUnavailable: '当前页面未成功跳转到支付宝。', alipayMobileUnavailable: '当前页面未成功跳转到支付宝。',
alipayMobileOpenHint: '请允许当前页面打开支付宝 App或改用系统浏览器重新发起支付。', alipayMobileOpenHint: '请允许当前页面打开支付宝 App或改用系统浏览器重新发起支付。',
// Structured error codes (reason strings from backend ApplicationError)
PAYMENT_DISABLED: '支付系统已关闭',
USER_INACTIVE: '账号已被禁用',
BALANCE_PAYMENT_DISABLED: '余额充值功能已关闭',
INVALID_AMOUNT: '金额无效',
INVALID_INPUT: '参数有误',
PLAN_NOT_AVAILABLE: '套餐不存在或已下架',
GROUP_NOT_FOUND: '订阅分组不可用',
GROUP_TYPE_MISMATCH: '分组类型不是订阅类型',
TOO_MANY_PENDING: '待支付订单过多(最多 {max} 个),请先完成或取消现有订单',
DAILY_LIMIT_EXCEEDED: '今日充值已达上限,剩余额度 {remaining}',
PAYMENT_GATEWAY_ERROR: '支付方式不可用',
NO_AVAILABLE_INSTANCE: '暂无可用的支付通道',
PAYMENT_PROVIDER_MISCONFIGURED: '支付通道配置错误,请联系管理员',
WXPAY_CONFIG_MISSING_KEY: '微信支付配置缺少必填项:{key}',
WXPAY_CONFIG_INVALID_KEY_LENGTH: '微信支付 {key} 长度错误,应为 {expected} 字节(实际 {actual}',
WXPAY_CONFIG_INVALID_KEY: '微信支付 {key} 格式错误,请确认复制了完整的 PEM 内容',
PENDING_ORDERS: '该服务商有未完成的订单,请等待订单完成后再操作', PENDING_ORDERS: '该服务商有未完成的订单,请等待订单完成后再操作',
PAYMENT_PROVIDER_CONFLICT: '该支付方式已有其他启用中的服务商实例,请先停用后再继续。', PAYMENT_PROVIDER_CONFLICT: '该支付方式已有其他启用中的服务商实例,请先停用后再继续。',
CANCEL_RATE_LIMITED: '取消订单过于频繁,请稍后再试',
NOT_FOUND: '订单不存在',
FORBIDDEN: '无权限操作此订单',
CONFLICT: '订单状态已变更,请刷新',
INVALID_ORDER_TYPE: '仅余额订单可申请退款',
INVALID_STATUS: '当前订单状态不允许此操作',
BALANCE_NOT_ENOUGH: '退款金额超过余额',
REFUND_AMOUNT_EXCEEDED: '退款金额超过充值金额',
REFUND_FAILED: '退款失败',
}, },
stripePay: '立即支付', stripePay: '立即支付',
stripeSuccessProcessing: '支付成功,正在处理订单...', stripeSuccessProcessing: '支付成功,正在处理订单...',

View File

@ -23,14 +23,96 @@ interface ApiErrorLike {
/** /**
* Extract the error code from an API error object. * Extract the error code from an API error object.
*
* Prefers the string `reason` (e.g. "PAYMENT_PROVIDER_MISCONFIGURED") over the
* numeric HTTP `code`, because reason is granular enough to drive i18n lookup
* while HTTP code is not.
*/ */
export function extractApiErrorCode(err: unknown): string | undefined { export function extractApiErrorCode(err: unknown): string | undefined {
if (!err || typeof err !== 'object') return undefined if (!err || typeof err !== 'object') return undefined
const e = err as ApiErrorLike const e = err as ApiErrorLike
const code = e.code ?? e.reason ?? e.response?.data?.code const code = e.reason ?? e.code ?? e.response?.data?.code
return code != null ? String(code) : undefined return code != null ? String(code) : undefined
} }
/**
* Extract metadata (interpolation params) from an API error object.
* Backend errors carry `metadata` with template variables that fill i18n placeholders.
*/
export function extractApiErrorMetadata(err: unknown): Record<string, unknown> | undefined {
if (!err || typeof err !== 'object') return undefined
const e = err as ApiErrorLike
return e.metadata
}
type TranslateFn = (key: string, params?: Record<string, unknown>) => string
type TranslateWithExistsFn = TranslateFn & { te?: (key: string) => boolean }
/**
* Translate a value via i18n if a matching key exists, otherwise return the original.
* Example: "certSerial" t('admin.settings.payment.field_certSerial') "证书序列号".
*/
function tryTranslate(t: TranslateFn, key: string, fallback: string): string {
const translated = t(key)
if (translated === key) return fallback
const te = (t as TranslateWithExistsFn).te
if (te && !te(key)) return fallback
return translated
}
/**
* Replace raw config field names in metadata (e.g. "certSerial") with their
* localized UI labels (e.g. "证书序列号"), using the provider-config field i18n namespace.
* Handles both single `key` and `/`-joined `keys` patterns used by wxpay errors.
*/
function localizeMetadata(metadata: Record<string, unknown>, t: TranslateFn): Record<string, unknown> {
const out: Record<string, unknown> = { ...metadata }
if (typeof out.key === 'string') {
out.key = tryTranslate(t, `admin.settings.payment.field_${out.key}`, out.key)
}
if (typeof out.keys === 'string') {
out.keys = out.keys
.split('/')
.map(k => tryTranslate(t, `admin.settings.payment.field_${k}`, k))
.join(' / ')
}
return out
}
/**
* Extract a localized error message from an API error by looking up
* `<namespace>.<REASON>` in i18n and substituting metadata as placeholders.
*
* Config-field names in metadata (`key` / `keys`) are automatically translated
* to their UI labels before substitution, so error messages read like
* "缺少必填项:证书序列号" instead of "缺少必填项certSerial".
*
* @param err - The caught error
* @param t - Vue i18n translate function
* @param namespace- i18n key prefix, e.g. "payment.errors"
* @param fallback - Fallback key or plain string if no localized mapping exists
*/
export function extractI18nErrorMessage(
err: unknown,
t: TranslateFn,
namespace: string,
fallback: string,
): string {
const code = extractApiErrorCode(err)
if (code) {
const key = `${namespace}.${code}`
const rawMetadata = extractApiErrorMetadata(err) ?? {}
const metadata = localizeMetadata(rawMetadata, t)
const translated = t(key, metadata)
// Vue i18n returns the key itself when missing; detect that and fall back.
if (translated !== key) return translated
// If the framework exposes `te`, use it to double-check.
const te = (t as TranslateWithExistsFn).te
if (te && te(key)) return translated
}
return extractApiErrorMessage(err, fallback)
}
/** /**
* Extract a displayable error message from an API error. * Extract a displayable error message from an API error.
* *

View File

@ -193,7 +193,9 @@ export function formatReasoningEffort(effort: string | null | undefined): string
return 'High' return 'High'
case 'xhigh': case 'xhigh':
case 'extrahigh': case 'extrahigh':
return 'Xhigh' return 'XHigh'
case 'max':
return 'Max'
case 'none': case 'none':
case 'minimal': case 'minimal':
return '-' return '-'

View File

@ -4710,7 +4710,7 @@ import ProxySelector from "@/components/common/ProxySelector.vue";
import ImageUpload from "@/components/common/ImageUpload.vue"; import ImageUpload from "@/components/common/ImageUpload.vue";
import BackupSettings from "@/views/admin/BackupView.vue"; import BackupSettings from "@/views/admin/BackupView.vue";
import { useClipboard } from "@/composables/useClipboard"; import { useClipboard } from "@/composables/useClipboard";
import { extractApiErrorMessage } from "@/utils/apiError"; import { extractApiErrorMessage, extractI18nErrorMessage } from "@/utils/apiError";
import { useAppStore } from "@/stores"; import { useAppStore } from "@/stores";
import { useAdminSettingsStore } from "@/stores/adminSettings"; import { useAdminSettingsStore } from "@/stores/adminSettings";
import { normalizeVisibleMethod } from "@/components/payment/paymentFlow"; import { normalizeVisibleMethod } from "@/components/payment/paymentFlow";
@ -6431,11 +6431,6 @@ const cancelRateLimitModeOptions = computed(() => [
}, },
]); ]);
const paymentErrorMap = computed(() => ({
PENDING_ORDERS: t("payment.errors.PENDING_ORDERS"),
PAYMENT_PROVIDER_CONFLICT: t("payment.errors.PAYMENT_PROVIDER_CONFLICT"),
}));
type ProviderEnablementCandidate = Pick< type ProviderEnablementCandidate = Pick<
ProviderInstance, ProviderInstance,
"id" | "provider_key" | "supported_types" | "enabled" | "name" "id" | "provider_key" | "supported_types" | "enabled" | "name"
@ -6531,7 +6526,7 @@ async function loadProviders() {
const res = await adminAPI.payment.getProviders(); const res = await adminAPI.payment.getProviders();
providers.value = res.data || []; providers.value = res.data || [];
} catch (err: unknown) { } catch (err: unknown) {
appStore.showError(extractApiErrorMessage(err, t("common.error"))); appStore.showError(extractI18nErrorMessage(err, t, "payment.errors", t("common.error")));
} finally { } finally {
providersLoading.value = false; providersLoading.value = false;
} }
@ -6580,9 +6575,7 @@ async function handleSaveProvider(payload: Partial<ProviderInstance>) {
// Auto-save settings so provider changes take effect immediately // Auto-save settings so provider changes take effect immediately
await saveSettings(); await saveSettings();
} catch (err: unknown) { } catch (err: unknown) {
appStore.showError( appStore.showError(extractI18nErrorMessage(err, t, "payment.errors", t("common.error")));
extractApiErrorMessage(err, t("common.error"), paymentErrorMap.value),
);
} finally { } finally {
providerSaving.value = false; providerSaving.value = false;
} }
@ -6620,9 +6613,7 @@ async function handleToggleField(
await adminAPI.payment.updateProvider(provider.id, payload); await adminAPI.payment.updateProvider(provider.id, payload);
await loadProviders(); await loadProviders();
} catch (err: unknown) { } catch (err: unknown) {
appStore.showError( appStore.showError(extractI18nErrorMessage(err, t, "payment.errors", t("common.error")));
extractApiErrorMessage(err, t("common.error"), paymentErrorMap.value),
);
} }
} }
@ -6647,9 +6638,7 @@ async function handleToggleType(provider: ProviderInstance, type: string) {
} as any); } as any);
await loadProviders(); await loadProviders();
} catch (err: unknown) { } catch (err: unknown) {
appStore.showError( appStore.showError(extractI18nErrorMessage(err, t, "payment.errors", t("common.error")));
extractApiErrorMessage(err, t("common.error"), paymentErrorMap.value),
);
} }
} }
@ -6671,7 +6660,7 @@ async function handleReorderProviders(
); );
await loadProviders(); await loadProviders();
} catch (err: unknown) { } catch (err: unknown) {
appStore.showError(extractApiErrorMessage(err, t("common.error"))); appStore.showError(extractI18nErrorMessage(err, t, "payment.errors", t("common.error")));
loadProviders(); loadProviders();
} }
} }
@ -6684,9 +6673,7 @@ async function handleDeleteProvider() {
showDeleteProviderDialog.value = false; showDeleteProviderDialog.value = false;
loadProviders(); loadProviders();
} catch (err: unknown) { } catch (err: unknown) {
appStore.showError( appStore.showError(extractI18nErrorMessage(err, t, "payment.errors", t("common.error")));
extractApiErrorMessage(err, t("common.error"), paymentErrorMap.value),
);
} }
} }

View File

@ -116,7 +116,7 @@ import { ref, reactive, computed, onMounted } from 'vue'
import { useI18n } from 'vue-i18n' import { useI18n } from 'vue-i18n'
import { useAppStore } from '@/stores/app' import { useAppStore } from '@/stores/app'
import { adminPaymentAPI } from '@/api/admin/payment' import { adminPaymentAPI } from '@/api/admin/payment'
import { extractApiErrorMessage } from '@/utils/apiError' import { extractI18nErrorMessage } from '@/utils/apiError'
import { formatOrderDateTime } from '@/components/payment/orderUtils' import { formatOrderDateTime } from '@/components/payment/orderUtils'
import type { PaymentOrder } from '@/types/payment' import type { PaymentOrder } from '@/types/payment'
import AppLayout from '@/components/layout/AppLayout.vue' import AppLayout from '@/components/layout/AppLayout.vue'
@ -167,7 +167,7 @@ async function loadOrders() {
orders.value = res.data.items || [] orders.value = res.data.items || []
orderPagination.total = res.data.total || 0 orderPagination.total = res.data.total || 0
} catch (err: unknown) { } catch (err: unknown) {
appStore.showError(extractApiErrorMessage(err, t('common.error'))) appStore.showError(extractI18nErrorMessage(err, t, 'payment.errors', t('common.error')))
} finally { ordersLoading.value = false } } finally { ordersLoading.value = false }
} }
@ -214,12 +214,12 @@ async function showOrderDetail(order: PaymentOrder) {
async function handleCancelOrder(order: PaymentOrder) { async function handleCancelOrder(order: PaymentOrder) {
try { await adminPaymentAPI.cancelOrder(order.id); appStore.showSuccess(t('payment.admin.orderCancelled')); loadOrders() } try { await adminPaymentAPI.cancelOrder(order.id); appStore.showSuccess(t('payment.admin.orderCancelled')); loadOrders() }
catch (err: unknown) { appStore.showError(extractApiErrorMessage(err, t('common.error'))) } catch (err: unknown) { appStore.showError(extractI18nErrorMessage(err, t, 'payment.errors', t('common.error'))) }
} }
async function handleRetryOrder(order: PaymentOrder) { async function handleRetryOrder(order: PaymentOrder) {
try { await adminPaymentAPI.retryRecharge(order.id); appStore.showSuccess(t('payment.admin.retrySuccess')); loadOrders() } try { await adminPaymentAPI.retryRecharge(order.id); appStore.showSuccess(t('payment.admin.retrySuccess')); loadOrders() }
catch (err: unknown) { appStore.showError(extractApiErrorMessage(err, t('common.error'))) } catch (err: unknown) { appStore.showError(extractI18nErrorMessage(err, t, 'payment.errors', t('common.error'))) }
} }
function openRefundDialog(order: PaymentOrder) { selectedOrder.value = order; showRefundDialog.value = true } function openRefundDialog(order: PaymentOrder) { selectedOrder.value = order; showRefundDialog.value = true }
@ -230,7 +230,7 @@ async function handleRefund(data: { amount: number; reason: string; deduct_balan
try { try {
await adminPaymentAPI.refundOrder(selectedOrder.value.id, { amount: data.amount, reason: data.reason, deduct_balance: data.deduct_balance, force: data.force }) await adminPaymentAPI.refundOrder(selectedOrder.value.id, { amount: data.amount, reason: data.reason, deduct_balance: data.deduct_balance, force: data.force })
appStore.showSuccess(t('payment.admin.refundSuccess')); showRefundDialog.value = false; loadOrders() appStore.showSuccess(t('payment.admin.refundSuccess')); showRefundDialog.value = false; loadOrders()
} catch (err: unknown) { appStore.showError(extractApiErrorMessage(err, t('common.error'))) } } catch (err: unknown) { appStore.showError(extractI18nErrorMessage(err, t, 'payment.errors', t('common.error'))) }
finally { refundSubmitting.value = false } finally { refundSubmitting.value = false }
} }

View File

@ -72,7 +72,7 @@ import { ref, watch, onMounted } from 'vue'
import { useI18n } from 'vue-i18n' import { useI18n } from 'vue-i18n'
import { useAppStore } from '@/stores/app' import { useAppStore } from '@/stores/app'
import { adminPaymentAPI } from '@/api/admin/payment' import { adminPaymentAPI } from '@/api/admin/payment'
import { extractApiErrorMessage } from '@/utils/apiError' import { extractI18nErrorMessage } from '@/utils/apiError'
import type { DashboardStats } from '@/types/payment' import type { DashboardStats } from '@/types/payment'
import AppLayout from '@/components/layout/AppLayout.vue' import AppLayout from '@/components/layout/AppLayout.vue'
import LoadingSpinner from '@/components/common/LoadingSpinner.vue' import LoadingSpinner from '@/components/common/LoadingSpinner.vue'
@ -110,7 +110,7 @@ async function loadDashboard() {
const res = await adminPaymentAPI.getDashboard(days.value) const res = await adminPaymentAPI.getDashboard(days.value)
stats.value = res.data stats.value = res.data
} catch (err: unknown) { } catch (err: unknown) {
appStore.showError(extractApiErrorMessage(err, t('common.error'))) appStore.showError(extractI18nErrorMessage(err, t, 'payment.errors', t('common.error')))
} finally { } finally {
loading.value = false loading.value = false
} }

View File

@ -78,7 +78,7 @@ import { ref, computed, onMounted } from 'vue'
import { useI18n } from 'vue-i18n' import { useI18n } from 'vue-i18n'
import { useAppStore } from '@/stores/app' import { useAppStore } from '@/stores/app'
import { adminPaymentAPI } from '@/api/admin/payment' import { adminPaymentAPI } from '@/api/admin/payment'
import { extractApiErrorMessage } from '@/utils/apiError' import { extractI18nErrorMessage } from '@/utils/apiError'
import adminAPI from '@/api/admin' import adminAPI from '@/api/admin'
import type { SubscriptionPlan } from '@/types/payment' import type { SubscriptionPlan } from '@/types/payment'
import type { AdminGroup } from '@/types' import type { AdminGroup } from '@/types'
@ -150,7 +150,7 @@ async function loadPlans() {
: (p.features || []), : (p.features || []),
})) }))
} }
catch (err: unknown) { appStore.showError(extractApiErrorMessage(err, t('common.error'))) } catch (err: unknown) { appStore.showError(extractI18nErrorMessage(err, t, 'payment.errors', t('common.error'))) }
finally { plansLoading.value = false } finally { plansLoading.value = false }
} }
@ -166,7 +166,7 @@ async function toggleForSale(plan: SubscriptionPlan) {
await adminPaymentAPI.updatePlan(plan.id, { for_sale: !plan.for_sale }) await adminPaymentAPI.updatePlan(plan.id, { for_sale: !plan.for_sale })
plan.for_sale = !plan.for_sale plan.for_sale = !plan.for_sale
} catch (err: unknown) { } catch (err: unknown) {
appStore.showError(extractApiErrorMessage(err, t('common.error'))) appStore.showError(extractI18nErrorMessage(err, t, 'payment.errors', t('common.error')))
} }
} }
@ -174,7 +174,7 @@ function confirmDeletePlan(plan: SubscriptionPlan) { deletingPlanId.value = plan
async function handleDeletePlan() { async function handleDeletePlan() {
if (!deletingPlanId.value) return if (!deletingPlanId.value) return
try { await adminPaymentAPI.deletePlan(deletingPlanId.value); appStore.showSuccess(t('common.deleted')); showDeletePlanDialog.value = false; loadPlans() } try { await adminPaymentAPI.deletePlan(deletingPlanId.value); appStore.showSuccess(t('common.deleted')); showDeletePlanDialog.value = false; loadPlans() }
catch (err: unknown) { appStore.showError(extractApiErrorMessage(err, t('common.error'))) } catch (err: unknown) { appStore.showError(extractI18nErrorMessage(err, t, 'payment.errors', t('common.error'))) }
} }
// ==================== Lifecycle ==================== // ==================== Lifecycle ====================

View File

@ -39,7 +39,7 @@ import { useRoute, useRouter } from 'vue-router'
import AppLayout from '@/components/layout/AppLayout.vue' import AppLayout from '@/components/layout/AppLayout.vue'
import { usePaymentStore } from '@/stores/payment' import { usePaymentStore } from '@/stores/payment'
import { paymentAPI } from '@/api/payment' import { paymentAPI } from '@/api/payment'
import { extractApiErrorMessage } from '@/utils/apiError' import { extractI18nErrorMessage } from '@/utils/apiError'
import { useAppStore } from '@/stores' import { useAppStore } from '@/stores'
import QRCode from 'qrcode' import QRCode from 'qrcode'
import alipayIcon from '@/assets/icons/alipay.svg' import alipayIcon from '@/assets/icons/alipay.svg'
@ -167,7 +167,7 @@ async function handleCancel() {
cleanup() cleanup()
router.push('/purchase') router.push('/purchase')
} catch (err: unknown) { } catch (err: unknown) {
appStore.showError(extractApiErrorMessage(err, t('common.error'))) appStore.showError(extractI18nErrorMessage(err, t, 'payment.errors', t('common.error')))
} finally { } finally {
cancelling.value = false cancelling.value = false
} }

View File

@ -252,13 +252,13 @@ import { usePaymentStore } from '@/stores/payment'
import { useSubscriptionStore } from '@/stores/subscriptions' import { useSubscriptionStore } from '@/stores/subscriptions'
import { useAppStore } from '@/stores' import { useAppStore } from '@/stores'
import { paymentAPI } from '@/api/payment' import { paymentAPI } from '@/api/payment'
import { extractApiErrorMessage } from '@/utils/apiError' import { extractApiErrorMessage, extractI18nErrorMessage } from '@/utils/apiError'
import { isMobileDevice } from '@/utils/device' import { isMobileDevice } from '@/utils/device'
import type { SubscriptionPlan, CheckoutInfoResponse, CreateOrderResult, OrderType } from '@/types/payment' import type { SubscriptionPlan, CheckoutInfoResponse, CreateOrderResult, OrderType } from '@/types/payment'
import AppLayout from '@/components/layout/AppLayout.vue' import AppLayout from '@/components/layout/AppLayout.vue'
import AmountInput from '@/components/payment/AmountInput.vue' import AmountInput from '@/components/payment/AmountInput.vue'
import PaymentMethodSelector from '@/components/payment/PaymentMethodSelector.vue' import PaymentMethodSelector from '@/components/payment/PaymentMethodSelector.vue'
import { METHOD_ORDER, POPUP_WINDOW_FEATURES, STRIPE_POPUP_WINDOW_FEATURES } from '@/components/payment/providerConfig' import { METHOD_ORDER, getPaymentPopupFeatures } from '@/components/payment/providerConfig'
import { import {
PAYMENT_RECOVERY_STORAGE_KEY, PAYMENT_RECOVERY_STORAGE_KEY,
buildCreateOrderPayload, buildCreateOrderPayload,
@ -630,8 +630,8 @@ async function createOrder(orderAmount: number, orderType: OrderType, planId?: n
payload.is_mobile = isMobileDevice() payload.is_mobile = isMobileDevice()
const result = await paymentStore.createOrder(payload) as CreateOrderResult & { resume_token?: string } const result = await paymentStore.createOrder(payload) as CreateOrderResult & { resume_token?: string }
const openWindow = (url: string, features = POPUP_WINDOW_FEATURES) => { const openWindow = (url: string) => {
const win = window.open(url, 'paymentPopup', features) const win = window.open(url, 'paymentPopup', getPaymentPopupFeatures())
if (!win || win.closed) { if (!win || win.closed) {
window.location.href = url window.location.href = url
} }
@ -672,7 +672,7 @@ async function createOrder(orderAmount: number, orderType: OrderType, planId?: n
persistRecoverySnapshot(decision.recovery) persistRecoverySnapshot(decision.recovery)
if (decision.kind === 'stripe_popup') { if (decision.kind === 'stripe_popup') {
openWindow(decision.paymentState.payUrl, STRIPE_POPUP_WINDOW_FEATURES) openWindow(decision.paymentState.payUrl)
return return
} }
if (decision.kind === 'stripe_route') { if (decision.kind === 'stripe_route') {
@ -710,8 +710,8 @@ async function createOrder(orderAmount: number, orderType: OrderType, planId?: n
err, err,
normalizeVisibleMethod(options.paymentType || selectedMethod.value) || selectedMethod.value, normalizeVisibleMethod(options.paymentType || selectedMethod.value) || selectedMethod.value,
) )
if (!errorMessage.value) { if (!handled) {
errorMessage.value = extractApiErrorMessage(err, t('payment.result.failed')) errorMessage.value = extractI18nErrorMessage(err, t, 'payment.errors', extractApiErrorMessage(err, t('payment.result.failed')))
errorHintMessage.value = '' errorHintMessage.value = ''
} }
if (handled) { if (handled) {
@ -825,7 +825,7 @@ onMounted(async () => {
} }
} }
} }
} catch (err: unknown) { appStore.showError(extractApiErrorMessage(err, t('common.error'))) } } catch (err: unknown) { appStore.showError(extractI18nErrorMessage(err, t, 'payment.errors', t('common.error'))) }
finally { loading.value = false } finally { loading.value = false }
// Fetch active subscriptions (uses cache, non-blocking) // Fetch active subscriptions (uses cache, non-blocking)
subscriptionStore.fetchActiveSubscriptions().catch(() => {}) subscriptionStore.fetchActiveSubscriptions().catch(() => {})

View File

@ -99,7 +99,7 @@ import { useI18n } from 'vue-i18n'
import { useRoute, useRouter } from 'vue-router' import { useRoute, useRouter } from 'vue-router'
import { usePaymentStore } from '@/stores/payment' import { usePaymentStore } from '@/stores/payment'
import { paymentAPI } from '@/api/payment' import { paymentAPI } from '@/api/payment'
import { extractApiErrorMessage } from '@/utils/apiError' import { extractI18nErrorMessage } from '@/utils/apiError'
import { isMobileDevice } from '@/utils/device' import { isMobileDevice } from '@/utils/device'
import type { PaymentOrder } from '@/types/payment' import type { PaymentOrder } from '@/types/payment'
import type { Stripe, StripeElements } from '@stripe/stripe-js' import type { Stripe, StripeElements } from '@stripe/stripe-js'
@ -167,7 +167,7 @@ onMounted(async () => {
mountPaymentElement(stripe, clientSecret) mountPaymentElement(stripe, clientSecret)
} }
} catch (err: unknown) { } catch (err: unknown) {
initError.value = extractApiErrorMessage(err, t('payment.stripeLoadFailed')) initError.value = extractI18nErrorMessage(err, t, 'payment.errors', t('payment.stripeLoadFailed'))
} finally { } finally {
loading.value = false loading.value = false
} }
@ -248,7 +248,7 @@ async function handleGenericPay() {
scheduleClose() scheduleClose()
} }
} catch (err: unknown) { } catch (err: unknown) {
stripeError.value = extractApiErrorMessage(err, t('payment.result.failed')) stripeError.value = extractI18nErrorMessage(err, t, 'payment.errors', t('payment.result.failed'))
} finally { } finally {
stripeSubmitting.value = false stripeSubmitting.value = false
} }

View File

@ -56,7 +56,7 @@
import { computed, ref, onMounted, onUnmounted } from 'vue' import { computed, ref, onMounted, onUnmounted } from 'vue'
import { useI18n } from 'vue-i18n' import { useI18n } from 'vue-i18n'
import { useRoute } from 'vue-router' import { useRoute } from 'vue-router'
import { extractApiErrorMessage } from '@/utils/apiError' import { extractI18nErrorMessage } from '@/utils/apiError'
import { isMobileDevice } from '@/utils/device' import { isMobileDevice } from '@/utils/device'
interface StripeWithWechatPay { interface StripeWithWechatPay {
@ -143,7 +143,7 @@ async function initStripe(clientSecret: string, publishableKey: string) {
} }
} }
} catch (err: unknown) { } catch (err: unknown) {
error.value = extractApiErrorMessage(err, t('payment.stripeLoadFailed')) error.value = extractI18nErrorMessage(err, t, 'payment.errors', t('payment.stripeLoadFailed'))
} }
} }

View File

@ -86,7 +86,7 @@ import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router' import { useRouter } from 'vue-router'
import { useAppStore } from '@/stores' import { useAppStore } from '@/stores'
import { paymentAPI } from '@/api/payment' import { paymentAPI } from '@/api/payment'
import { extractApiErrorMessage } from '@/utils/apiError' import { extractI18nErrorMessage } from '@/utils/apiError'
import type { PaymentOrder } from '@/types/payment' import type { PaymentOrder } from '@/types/payment'
import AppLayout from '@/components/layout/AppLayout.vue' import AppLayout from '@/components/layout/AppLayout.vue'
import Pagination from '@/components/common/Pagination.vue' import Pagination from '@/components/common/Pagination.vue'
@ -128,7 +128,7 @@ async function fetchOrders() {
orders.value = res.data.items || [] orders.value = res.data.items || []
pagination.total = res.data.total || 0 pagination.total = res.data.total || 0
} catch (err: unknown) { } catch (err: unknown) {
appStore.showError(extractApiErrorMessage(err, t('common.error'))) appStore.showError(extractI18nErrorMessage(err, t, 'payment.errors', t('common.error')))
} finally { } finally {
loading.value = false loading.value = false
} }
@ -148,7 +148,7 @@ async function confirmCancel() {
cancelTargetId.value = null cancelTargetId.value = null
await fetchOrders() await fetchOrders()
} catch (err: unknown) { } catch (err: unknown) {
appStore.showError(extractApiErrorMessage(err, t('common.error'))) appStore.showError(extractI18nErrorMessage(err, t, 'payment.errors', t('common.error')))
} finally { } finally {
actionLoading.value = false actionLoading.value = false
} }
@ -166,7 +166,7 @@ async function confirmRefund() {
refundReason.value = '' refundReason.value = ''
await fetchOrders() await fetchOrders()
} catch (err: unknown) { } catch (err: unknown) {
appStore.showError(extractApiErrorMessage(err, t('common.error'))) appStore.showError(extractI18nErrorMessage(err, t, 'payment.errors', t('common.error')))
} finally { } finally {
actionLoading.value = false actionLoading.value = false
} }