Skip to content

feat: 自定义充值方式 - #1257

Merged
Calcium-Ion merged 1 commit into
alphafrom
pay_custom
Jun 19, 2025
Merged

Calcium-Ion merged 1 commit into
alphafrom
pay_custom

Conversation

@creamlike1024

@creamlike1024 creamlike1024 commented Jun 18, 2025 •

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • New Features
    • Added configurable payment methods that can be managed in system settings and input as JSON.
    • Payment method options in the Top-Up page are now dynamically loaded and displayed based on configuration, supporting more than just Alipay and WeChat.
  • Bug Fixes
    • Improved error handling when loading payment methods from local storage, with user-facing error messages for invalid configurations.
  • Style
    • Consistent use of single quotes in JSX and code formatting improvements in the Top-Up page.
  • Documentation
    • Added inline descriptions for new payment method configuration options in the settings UI.

@coderabbitai

coderabbitai Bot commented Jun 18, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

This change introduces a configurable payment methods system across backend and frontend. The backend adds a global PayMethods variable, exposes it via API responses, and allows updates through options. The frontend dynamically loads, displays, and validates payment methods from JSON, replacing previously hardcoded options with a flexible, user-editable configuration.

Changes

File(s) Change Summary
controller/misc.go Adds pay_methods field to JSON response in GetStatus, sourced from setting.PayMethods.
model/option.go Integrates "PayMethods" into option map initialization and update logic.
setting/payment.go Introduces global PayMethods variable and functions for JSON serialization, update, and lookup.
web/src/components/settings/SystemSetting.js Adds PayMethods config field, validation, and UI for JSON input in system settings.
web/src/helpers/data.js Stores pay_methods from API response into localStorage as JSON string.
web/src/pages/TopUp/index.js Refactors payment method UI to dynamically load and display methods from localStorage JSON.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant SystemSettingUI
    participant BackendAPI
    participant OptionMap
    participant PaymentSetting

    User->>SystemSettingUI: Edits PayMethods JSON
    SystemSettingUI->>BackendAPI: Submits updated PayMethods
    BackendAPI->>OptionMap: updateOptionMap("PayMethods", value)
    OptionMap->>PaymentSetting: UpdatePayMethodsByJsonString(value)
    PaymentSetting-->>OptionMap: PayMethods updated
    BackendAPI-->>SystemSettingUI: Responds with status including pay_methods
    SystemSettingUI-->>User: Shows updated payment methods
Loading
sequenceDiagram
    participant User
    participant TopUpUI
    participant LocalStorage

    TopUpUI->>LocalStorage: Reads 'pay_methods' JSON
    LocalStorage-->>TopUpUI: Returns payment methods array
    TopUpUI-->>User: Displays dynamic payment buttons
    User->>TopUpUI: Selects payment method
    TopUpUI-->>User: Shows confirmation modal with selected method
Loading

Poem

In fields of code, new methods bloom,
Payment options now resume!
JSON strings and colors bright,
Hop into settings—edit, delight.
From backend roots to frontend view,
Flexible payments—fresh and new!
—🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

♻️ Duplicate comments (1)
model/option.go (1)

82-82: Initial option value will desync once struct refactor lands

Storing the raw JSON string is fine, but when PayMethod becomes a struct (see earlier comment), remember to call the new PayMethods2JsonString() here to avoid stale format assumptions.

🧹 Nitpick comments (10)
web/src/helpers/data.js (1)

12-12: Guard against absent value to avoid "undefined" pollution

If the backend ever omits pay_methods, JSON.stringify(undefined) yields undefined (string), not null, which later JSON.parse will choke on.

-  localStorage.setItem('pay_methods', JSON.stringify(data.pay_methods));
+  if (data.pay_methods !== undefined) {
+    localStorage.setItem('pay_methods', JSON.stringify(data.pay_methods));
+  } else {
+    localStorage.removeItem('pay_methods');
+  }
model/option.go (1)

392-394: Bubble up JSON parse errors for admin feedback

UpdatePayMethodsByJsonString now (after fix) returns an error when JSON is invalid, but the UI currently only logs a generic “更新失败”. Consider surfacing the specific parse error so the admin instantly knows the JSON is malformed.

web/src/components/settings/SystemSetting.js (4)

20-21: verifyJSON might not be tree-shake-safe

Importing the helper solely for two verifications can increase bundle size if verifyJSON sits in a large utilities file. Consider a lean sub-module export (e.g. helpers/json) to keep chunks small.


234-239: Duplicate JSON validation logic – abstract to reduce drift

Both TopupGroupRatio and PayMethods share the "changed && verifyJSON" pattern. Extract a small helper:

const needValidJson = (key) =>
  originInputs[key] !== inputs[key] && !verifyJSON(inputs[key]);

This keeps the form logic concise and avoids future copy-paste mistakes.


266-268: Push prettified JSON for better readability in DB and logs

Before options.push({ key: 'PayMethods', value: inputs.PayMethods });
consider:

options.push({
  key: 'PayMethods',
  value: JSON.stringify(JSON.parse(inputs.PayMethods), null, 2),
});

This keeps the stored string human readable.


671-676: UI placeholder could link to schema for easier editing

Admins may not know the expected keys (name, color, type). Add a short hint or example JSON in the placeholder/description to prevent invalid submissions.

web/src/pages/TopUp/index.js (4)

52-60: Avoid duplicating min_topup in state initialisation.
minTopUp is already initialised just above. Instead of copying the literal again (which can drift), derive the initial topUpCount from that state so there is a single source of truth:

-const [topUpCount, setTopUpCount] = useState(
-  statusState?.status?.min_topup || 1,
-);
+const [topUpCount, setTopUpCount] = useState(() => statusState?.status?.min_topup || 1);

This keeps the default in sync even if the backend changes its minimum.


70-70: Variable-name shadowing can confuse future readers.
payMethods is used both as a local variable later and as a React state setter (setPayMethods). Consider renaming the local variable to storedPayMethods (or similar) to avoid shadowing.


688-711: Duplicate payment-button markup – extract a component.
The desktop and mobile sections render the same “pay method” button grid. Extract a small <PayMethodButtons payMethods … /> component to DRY this up and keep behaviour consistent.

Also applies to: 963-985


618-662: InputNumber parser can return NaN.
If the user erases the field completely the parser returns 0, but onChange treats falsy as invalid which leaves 0 in state. Consider guarding with Number.isFinite(value) or coercing to undefined to avoid topUpCount = 0.

Also applies to: 913-941

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0bca4d3 and 9708d64.

📒 Files selected for processing (6)
  • controller/misc.go (1 hunks)
  • model/option.go (2 hunks)
  • setting/payment.go (1 hunks)
  • web/src/components/settings/SystemSetting.js (5 hunks)
  • web/src/helpers/data.js (1 hunks)
  • web/src/pages/TopUp/index.js (17 hunks)
🔇 Additional comments (5)
controller/misc.go (1)

79-80: Confirm frontend/key naming consistency

A new response field "pay_methods" is added. Ensure:

  • Frontend always lower-cases when reading (looks OK in helpers/data.js).
  • No existing clients relied on camelCase (payMethods) – breaking change risk.

If any public API consumers exist, consider versioning or aliasing for backward compatibility.

web/src/pages/TopUp/index.js (4)

10-11: Imports look good.
The new helpers (getQuotaPerUnit) and the Coins icon are correctly pulled in and alphabetically consistent with the surrounding imports.

Also applies to: 37-38


86-87: 👍 Extra preset is harmless.
Adding the 1000-quota preset is straightforward and doesn’t touch validation logic.


136-137: Potential stale state when updating user quota.
userState.user.quota is read synchronously inside setUserQuota, but userState.user may already be stale at this point. Prefer reading the fresh value from updatedUser or using a functional update on userDispatch.


385-404: UI tweaks only.
Nothing functionally risky in these cosmetic changes.

Also applies to: 431-441

Comment thread setting/payment.go
Comment on lines +12 to +23
var PayMethods = []map[string]string{
{
"name": "支付宝",
"color": "rgba(var(--semi-blue-5), 1)",
"type": "zfb",
},
{
"name": "微信",
"color": "rgba(var(--semi-green-5), 1)",
"type": "wx",
},
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider replacing map[string]string with a dedicated struct for type-safety

The slice is currently defined as []map[string]string.
Pros of introducing a type PayMethod struct { Name string; Color string; Type string }:

  • Compile-time guarantees that every entry contains the three expected keys.
  • No magic strings when accessing fields elsewhere (pm.Type vs. m["type"]).
  • Easier JSON (un)marshalling and future refactors.

Refactoring now will avoid scattered map look-ups in the future.

🤖 Prompt for AI Agents
In setting/payment.go around lines 12 to 23, replace the slice of
map[string]string with a slice of a dedicated struct named PayMethod that has
fields Name, Color, and Type all of type string. Define the PayMethod struct
above the slice declaration, then update the slice to use PayMethod instances
instead of maps. This change will enforce type safety, eliminate string key
lookups, and simplify future maintenance and JSON handling.

Comment thread setting/payment.go
Comment on lines +25 to +45
func UpdatePayMethodsByJsonString(jsonString string) error {
PayMethods = make([]map[string]string, 0)
return json.Unmarshal([]byte(jsonString), &PayMethods)
}

func PayMethods2JsonString() string {
jsonBytes, err := json.Marshal(PayMethods)
if err != nil {
return "[]"
}
return string(jsonBytes)
}

func ContainsPayMethod(method string) bool {
for _, payMethod := range PayMethods {
if payMethod["type"] == method {
return true
}
}
return false
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Unprotected global mutation & potential data-loss in UpdatePayMethodsByJsonString

  1. A failed json.Unmarshal leaves PayMethods reset to an empty slice, silently wiping existing config.
  2. Concurrent reads (e.g. from HTTP handlers) and this write introduce a clear data race.

Proposed fix (simplified):

+var payMethodsMu sync.RWMutex
+
 func UpdatePayMethodsByJsonString(jsonString string) error {
-    PayMethods = make([]map[string]string, 0)
-    return json.Unmarshal([]byte(jsonString), &PayMethods)
+    var methods []map[string]string
+    if err := json.Unmarshal([]byte(jsonString), &methods); err != nil {
+        return err
+    }
+    payMethodsMu.Lock()
+    PayMethods = methods
+    payMethodsMu.Unlock()
+    return nil
 }
 
 func PayMethods2JsonString() string {
-    jsonBytes, err := json.Marshal(PayMethods)
+    payMethodsMu.RLock()
+    jsonBytes, err := json.Marshal(PayMethods)
+    payMethodsMu.RUnlock()
@@
 }
 
 func ContainsPayMethod(method string) bool {
-    for _, payMethod := range PayMethods {
+    payMethodsMu.RLock()
+    defer payMethodsMu.RUnlock()
+    for _, payMethod := range PayMethods {
         if payMethod["type"] == method {
             return true
         }
     }
     return false
 }

This preserves the old value on parse failure and removes the race condition.

🤖 Prompt for AI Agents
In setting/payment.go around lines 25 to 45, the UpdatePayMethodsByJsonString
function resets the global PayMethods slice before unmarshaling, which causes
data loss if unmarshaling fails, and also introduces a data race with concurrent
reads. To fix this, first unmarshal the JSON into a local variable, check for
errors, and only update the global PayMethods if unmarshaling succeeds.
Additionally, protect access to PayMethods with appropriate synchronization
(e.g., a mutex) to prevent data races during concurrent reads and writes.

Comment on lines +294 to 321
let payMethods = localStorage.getItem('pay_methods');
try {
payMethods = JSON.parse(payMethods);
if (payMethods && payMethods.length > 0) {
// 检查name和type是否为空
payMethods = payMethods.filter((method) => {
return method.name && method.type;
});
// 如果没有color,则设置默认颜色
payMethods = payMethods.map((method) => {
if (!method.color) {
if (method.type === 'zfb') {
method.color = 'rgba(var(--semi-blue-5), 1)';
} else if (method.type === 'wx') {
method.color = 'rgba(var(--semi-green-5), 1)';
} else {
method.color = 'rgba(var(--semi-primary-5), 1)';
}
}
return method;
});
setPayMethods(payMethods);
}
} catch (e) {
console.log(e);
showError(t('支付方式配置错误, 请联系管理员'));
}
}, []);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Sanitise & de-duplicate pay_methods parsing.

  1. Shadowing (payMethods vs. state) and in-place mutation make this block hard to reason about.
  2. method.color is injected directly into an inline style; a crafted colour such as url(javascript:alert(1)) would be executed by some browsers. Validate that the value matches a safe CSS colour format.
-    let payMethods = localStorage.getItem('pay_methods');
-    try {
-      payMethods = JSON.parse(payMethods);
-      if (payMethods && payMethods.length > 0) {
+    const raw = localStorage.getItem('pay_methods');
+    try {
+      const storedPayMethods = JSON.parse(raw);
+      if (Array.isArray(storedPayMethods) && storedPayMethods.length) {
         // …
-        setPayMethods(payMethods);
+        setPayMethods(sanitisedPayMethods);
       }

Add a simple colour whitelist, e.g. regex /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i or limit to known CSS variables.

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In web/src/pages/TopUp/index.js around lines 294 to 321, the code mutates the
payMethods array directly and shadows the variable name, making it confusing.
Also, the method.color value is assigned without validation, which can lead to
security risks if malicious values are injected. To fix this, avoid mutating the
original array by creating a new sanitized array for state update, rename
variables to prevent shadowing, and implement a whitelist check for method.color
values using a regex that only allows safe CSS color formats or restrict to
known CSS variables before assigning them.

@Calcium-Ion Calcium-Ion changed the title 充值方式设置 feat: 自定义充值方式 Jun 19, 2025
@Calcium-Ion
Calcium-Ion marked this pull request as ready for review June 19, 2025 06:31
@Calcium-Ion
Calcium-Ion merged commit da002e6 into alpha Jun 19, 2025
@creamlike1024
creamlike1024 deleted the pay_custom branch June 21, 2025 03:17
This was referenced Sep 27, 2025
x22x22 pushed a commit to x22x22/new-api that referenced this pull request Apr 24, 2026
@coderabbitai coderabbitai Bot mentioned this pull request Apr 29, 2026
8 of 11 tasks
@coderabbitai coderabbitai Bot mentioned this pull request Jul 13, 2026
8 of 11 tasks
salem-2007 added a commit to salem-2007/new-api that referenced this pull request Sep 10, 2026
junjundesk pushed a commit to junjundesk/new-api that referenced this pull request Oct 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants