Skip to content

Add stripe support and fix wrong top up loading state - #1352

Merged
creamlike1024 merged 8 commits into
QuantumNous:alphafrom
wzxjohn:feature/simple_stripe
Jul 18, 2025
Merged

creamlike1024 merged 8 commits into
QuantumNous:alphafrom
wzxjohn:feature/simple_stripe

Conversation

@wzxjohn

@wzxjohn wzxjohn commented Jul 10, 2025 •

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • New Features

    • Added support for Stripe as an online top-up payment method, including payment processing, webhook handling, and user group-based pricing.
    • Introduced Stripe payment settings in the admin panel for API credentials, product price, unit price, and minimum top-up amount.
    • Added new API endpoints for Stripe payment and webhook integration.
    • Extended user and top-up management to support Stripe customer IDs, unique payment references, completion timestamps, and payment status tracking.
    • Added cryptographic utilities for hashing and HMAC operations.
  • Enhancements

    • Updated status endpoint and top-up page UI to display Stripe-related payment options and configuration.
    • Applied rate limiting to payment-related API routes for improved security.
  • Chores

    • Added new dependencies for Stripe integration and cryptographic utilities.

@coderabbitai

coderabbitai Bot commented Jul 10, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

This update introduces Stripe payment gateway integration for top-up functionality, affecting both backend and frontend. Backend changes add Stripe configuration, payment processing, webhook handling, and related database/model logic. Frontend changes extend payment settings and top-up flows to support Stripe, including new UI components and state management for Stripe-specific fields and user interactions.

Changes

File(s) Change Summary
common/constants.go Added string constants for top-up statuses: pending, success, expired.
common/hash.go New file: cryptographic hash and HMAC utility functions.
controller/misc.go Extended status endpoint to include Stripe config and enablement flag.
controller/topup_stripe.go New file: Implements Stripe payment integration, handlers, and webhook logic.
go.mod Added dependencies: stripe-go, randstr, x/sync; removed indirect x/sync.
model/option.go Added Stripe config options to option map initialization and update logic.
model/topup.go Extended TopUp struct (unique TradeNo, CompleteTime); added Recharge function for Stripe top-up completion.
model/user.go Added StripeCustomer field (with DB index) to User struct.
router/api-router.go Added Stripe endpoints; applied rate limiting to payment routes.
setting/payment_stripe.go New file: Declares Stripe config variables (API secret, webhook secret, price ID, unit price, min top-up).
web/src/components/settings/PaymentSetting.js Extended PaymentSetting component to handle Stripe config and render Stripe settings UI.
web/src/pages/Setting/Payment/SettingsPaymentGatewayStripe.js New component: Stripe payment gateway settings form with API integration and validation.
web/src/pages/TopUp/index.js Extended TopUp page with Stripe top-up flow, state, and modal UI; added Stripe payment logic and handlers.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Frontend
    participant Backend
    participant Stripe

    User->>Frontend: Initiate Stripe Top-Up
    Frontend->>Backend: POST /user/self/stripe/amount (get payable amount)
    Backend-->>Frontend: Return calculated Stripe amount
    User->>Frontend: Confirm Stripe payment
    Frontend->>Backend: POST /user/self/stripe/pay (request payment)
    Backend->>Stripe: Create Checkout Session
    Stripe-->>Backend: Return payment link
    Backend-->>Frontend: Return payment link
    Frontend->>User: Redirect to Stripe payment page

    Stripe->>Backend: POST /stripe/webhook (payment completed/expired)
    Backend->>Backend: Verify event, update order status, recharge quota if success
Loading

Poem

🐇
With Stripe we hop to pay anew,
New fields and forms, a gateway true.
Webhooks dance and models grow,
Hashes, secrets, status flow.
In every code and UI part—
A top-up leap, a Stripe-y start!


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8be8813 and fb9b5d3.

📒 Files selected for processing (4)
  • controller/misc.go (2 hunks)
  • router/api-router.go (2 hunks)
  • web/src/components/settings/PaymentSetting.js (4 hunks)
  • web/src/pages/TopUp/index.js (9 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • web/src/components/settings/PaymentSetting.js
  • router/api-router.go
  • controller/misc.go
  • web/src/pages/TopUp/index.js
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 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.

@wzxjohn
wzxjohn changed the base branch from main to alpha July 10, 2025 12:35

@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: 9

🔭 Outside diff range comments (1)
go.mod (1)

4-4: Invalid Go version directive – replace 1.23.4 with a minor‐only version.

go.mod only accepts major.minor (e.g. go 1.23). The additional patch component will break go commands (go: malformed go version).

-go 1.23.4
+go 1.23
🧹 Nitpick comments (6)
common/hash.go (2)

16-20: Redundant conversion & naming mismatch in Sha1Raw.

data is already []byte; []byte(data) allocates for no reason. Also, the pair Sha256Raw(string) vs Sha1Raw([]byte) is asymmetric (see previous comment).

- h.Write([]byte(data))
+ h.Write(data)

26-34: Minor: avoid repetitive byte slicing inside HMAC helper.

HmacSha256 currently converts both args on every call; offer a friendlier typed wrapper or drop the helper entirely to avoid misuse with UTF-8 vs raw bytes.

web/src/pages/Setting/Payment/SettingsPaymentGatewayStripe.js (2)

17-17: Remove unused import

The verifyJSON function is imported but never used in this component.

-  verifyJSON,

99-99: Use optional chaining for cleaner code

-        props.refresh && props.refresh();
+        props.refresh?.();
controller/topup_stripe.go (1)

184-187: Use idiomatic Go for empty string check

-	if "" == referenceId {
+	if len(referenceId) == 0 {
 		log.Println("未提供支付单号")
 		return
 	}
web/src/pages/TopUp/index.js (1)

941-954: Simplify complex conditional rendering

The nested ternary operator makes the code hard to read. Consider extracting the divider text logic.

-                      {!enableOnlineTopUp?(
-                          <Divider style={{ margin: '24px 0' }}>
-                            <Text className='text-sm font-medium'>
-                              {t('或输入自定义金额')}
-                            </Text>
-                          </Divider>
-                      ) : (
-                          <Divider style={{ margin: '24px 0' }}>
-                            <Text className='text-sm font-medium'>
-                              {t('Stripe')}
-                            </Text>
-                          </Divider>
-                      )
-                      }
+                      <Divider style={{ margin: '24px 0' }}>
+                        <Text className='text-sm font-medium'>
+                          {t(!enableOnlineTopUp ? '或输入自定义金额' : 'Stripe')}
+                        </Text>
+                      </Divider>
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 78fb457 and d6ed2ab.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (13)
  • common/constants.go (1 hunks)
  • common/hash.go (1 hunks)
  • controller/misc.go (2 hunks)
  • controller/topup_stripe.go (1 hunks)
  • go.mod (1 hunks)
  • model/option.go (2 hunks)
  • model/topup.go (2 hunks)
  • model/user.go (1 hunks)
  • router/api-router.go (2 hunks)
  • setting/payment_stripe.go (1 hunks)
  • web/src/components/settings/PaymentSetting.js (4 hunks)
  • web/src/pages/Setting/Payment/SettingsPaymentGatewayStripe.js (1 hunks)
  • web/src/pages/TopUp/index.js (9 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (5)
model/option.go (2)
common/constants.go (1)
  • OptionMap (36-36)
setting/payment_stripe.go (5)
  • StripeMinTopUp (7-7)
  • StripeApiSecret (3-3)
  • StripeWebhookSecret (4-4)
  • StripePriceId (5-5)
  • StripeUnitPrice (6-6)
web/src/pages/Setting/Payment/SettingsPaymentGatewayStripe.js (2)
web/src/components/settings/PaymentSetting.js (3)
  • useTranslation (10-10)
  • loading (29-29)
  • inputs (11-27)
web/src/helpers/utils.js (3)
  • showError (94-123)
  • showSuccess (129-131)
  • a (231-231)
controller/misc.go (2)
setting/payment_stripe.go (5)
  • StripeUnitPrice (6-6)
  • StripeMinTopUp (7-7)
  • StripeApiSecret (3-3)
  • StripeWebhookSecret (4-4)
  • StripePriceId (5-5)
setting/payment.go (1)
  • MinTopUp (10-10)
web/src/components/settings/PaymentSetting.js (2)
web/src/pages/Setting/Payment/SettingsPaymentGateway.js (1)
  • inputs (23-32)
web/src/pages/Setting/Payment/SettingsPaymentGatewayStripe.js (1)
  • inputs (24-30)
controller/topup_stripe.go (8)
controller/topup.go (1)
  • RequestAmount (241-265)
model/user.go (3)
  • GetUserGroup (607-632)
  • GetUserById (224-236)
  • User (18-47)
setting/payment_stripe.go (5)
  • StripeMinTopUp (7-7)
  • StripeWebhookSecret (4-4)
  • StripeApiSecret (3-3)
  • StripePriceId (5-5)
  • StripeUnitPrice (6-6)
common/hash.go (1)
  • Sha1 (22-24)
model/topup.go (3)
  • TopUp (10-19)
  • Recharge (53-99)
  • GetTopUpByTradeNo (43-51)
common/constants.go (4)
  • TopUpStatusPending (198-198)
  • TopUpStatusExpired (200-200)
  • DisplayInCurrencyEnabled (22-22)
  • QuotaPerUnit (21-21)
setting/system_setting.go (1)
  • ServerAddress (3-3)
common/topup-ratio.go (1)
  • GetTopupGroupRatio (26-33)
🪛 Biome (1.9.4)
web/src/pages/Setting/Payment/SettingsPaymentGatewayStripe.js

[error] 102-104: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (8)
go.mod (1)

30-36: No action required – go.mod is up-to-date

I ran go mod tidy and confirmed there are no unstaged changes in both go.mod and go.sum. All newly added dependencies are properly tracked and unused modules have been pruned.

common/constants.go (1)

197-201: LGTM – centralised status strings aid consistency.

web/src/components/settings/PaymentSetting.js (1)

5-5: Well-structured Stripe integration following existing patterns

The Stripe payment gateway integration follows the established pattern used for other payment methods. The state management, data parsing, and UI rendering are consistent with the existing codebase structure.

Also applies to: 21-26, 48-49, 92-94

controller/misc.go (1)

60-60: Secure Stripe configuration exposure

The implementation correctly validates all required Stripe configuration fields before enabling the feature, ensuring that Stripe payments are only available when properly configured.

Also applies to: 62-62, 76-76

model/option.go (1)

78-82: Consistent Stripe option management implementation

The Stripe configuration options are properly integrated into the existing option management system with correct type conversions for numeric fields.

Also applies to: 316-325

model/topup.go (1)

3-8: Robust transactional top-up implementation

The Recharge function implements a well-designed transactional flow with:

  • Proper concurrency control using FOR UPDATE lock
  • Atomic updates to both top-up status and user quota
  • Prevention of duplicate transactions via unique constraint on TradeNo
  • Comprehensive error handling and transaction rollback

The implementation effectively prevents race conditions and ensures data consistency.

Also applies to: 15-15, 17-17, 53-99

router/api-router.go (1)

41-41: Well-designed Stripe routing with appropriate security measures

The routing configuration correctly:

  • Excludes rate limiting for the webhook endpoint (required for external Stripe callbacks)
  • Applies critical rate limiting to payment initiation endpoints
  • Appropriately structures the new Stripe endpoints under the authenticated user routes

Also applies to: 62-63, 65-66

controller/topup_stripe.go (1)

209-245: Well-structured Stripe checkout session creation

The function properly validates the API key format and handles both existing and new customer scenarios correctly.

Comment thread common/hash.go Resolved
Comment thread model/user.go Resolved
Comment thread setting/payment_stripe.go
Comment on lines +3 to +7
var StripeApiSecret = ""
var StripeWebhookSecret = ""
var StripePriceId = ""
var StripeUnitPrice = 8.0
var StripeMinTopUp = 1

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

Store secrets outside the binary & avoid float price.

  1. Hard-coding StripeApiSecret / StripeWebhookSecret leaks credentials when logs or panic dumps print globals. Prefer env vars or an encrypted config source.
  2. Monetary values should use integer cents or decimal.Decimal, not float64, to avoid rounding errors.
-var StripeApiSecret = ""
-var StripeWebhookSecret = ""
+// set via option loader or env (never commit real secrets)
+var StripeApiSecret string
+var StripeWebhookSecret string

-var StripeUnitPrice = 8.0
+// in minor currency unit, e.g. cents
+var StripeUnitPriceCents = 800
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
var StripeApiSecret = ""
var StripeWebhookSecret = ""
var StripePriceId = ""
var StripeUnitPrice = 8.0
var StripeMinTopUp = 1
// set via option loader or env (never commit real secrets)
var StripeApiSecret string
var StripeWebhookSecret string
var StripePriceId = ""
// in minor currency unit, e.g. cents
var StripeUnitPriceCents = 800
var StripeMinTopUp = 1
🤖 Prompt for AI Agents
In setting/payment_stripe.go around lines 3 to 7, avoid hard-coding
StripeApiSecret and StripeWebhookSecret as global variables to prevent
credential leaks; instead, load these secrets from environment variables or a
secure encrypted configuration source. Also, replace the float64 StripeUnitPrice
with an integer representing the price in cents or use a decimal.Decimal type to
accurately handle monetary values and prevent rounding errors.

Comment thread controller/topup_stripe.go Resolved
Comment thread controller/topup_stripe.go Resolved
Comment thread web/src/pages/TopUp/index.js Resolved
Comment thread web/src/pages/TopUp/index.js Resolved

@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: 2

🧹 Nitpick comments (2)
web/src/pages/TopUp/index.js (2)

437-461: Clean up formatting and remove empty finally block.

The function has inconsistent spacing and an empty finally block that should be removed.

         if (message === 'success') {
-          setStripeAmount(parseFloat(data))
+          setStripeAmount(parseFloat(data));
         } else {
-          setStripeAmount( 0)
+          setStripeAmount(0);
           Toast.error({ content: '错误:' + data, id: 'getAmount' });
         }
       } else {
         showError(res);
       }
     } catch (err) {
       console.log(err);
-    } finally {
-    }
+    }
   }

605-622: Consider enhancing the Stripe modal with payment method display.

The Stripe confirmation modal shows basic information but could benefit from displaying the payment method name for better user clarity, similar to the existing online top-up modal.

       <p>
         {t('充值数量')}:{stripeTopUpCount}
       </p>
       <p>
         {t('实付金额')}:{renderStripeAmount()}
       </p>
+      <p>
+        {t('支付方式')}:Stripe
+      </p>
       <p>{t('是否确认充值?')}</p>
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d6ed2ab and 8cc747e.

📒 Files selected for processing (5)
  • common/hash.go (1 hunks)
  • controller/topup_stripe.go (1 hunks)
  • model/user.go (1 hunks)
  • web/src/pages/Setting/Payment/SettingsPaymentGatewayStripe.js (1 hunks)
  • web/src/pages/TopUp/index.js (9 hunks)
✅ Files skipped from review due to trivial changes (1)
  • model/user.go
🚧 Files skipped from review as they are similar to previous changes (3)
  • common/hash.go
  • web/src/pages/Setting/Payment/SettingsPaymentGatewayStripe.js
  • controller/topup_stripe.go
🔇 Additional comments (5)
web/src/pages/TopUp/index.js (5)

295-297: Good implementation of external redirect handling.

The use of window.open() instead of location.href properly preserves application state and opens the payment link in a new tab, which is the correct approach for external payment redirects.


480-482: Excellent synchronization of preset amounts.

The implementation correctly synchronizes both regular and Stripe top-up amounts when a preset is selected, ensuring consistent user experience across payment methods.


926-935: Correct conditional logic for payment method availability.

The banner correctly displays only when both online top-up and Stripe top-up are disabled, providing appropriate user guidance.


937-1018: Well-structured Stripe payment UI implementation.

The Stripe payment section follows the same pattern as the existing online top-up UI, providing consistent user experience. The conditional rendering, input validation, and button states are properly implemented.


961-961: Correct disabled prop usage for Stripe input.

The disabled prop correctly uses enableStripeTopUp instead of enableOnlineTopUp, which properly controls the input state based on Stripe availability.

Comment thread web/src/pages/TopUp/index.js Resolved
Comment thread web/src/pages/TopUp/index.js Resolved
@creamlike1024
creamlike1024 merged commit 952b679 into QuantumNous:alpha Jul 18, 2025
@wzxjohn
wzxjohn deleted the feature/simple_stripe branch August 27, 2025 01:59
x22x22 pushed a commit to x22x22/new-api that referenced this pull request Apr 24, 2026
Add stripe support and fix wrong top up loading state
jiutubaba pushed a commit to jiutubaba/fx-api that referenced this pull request May 17, 2026
…oad-oauth-scope

Feat/add file upload oauth scope
@coderabbitai coderabbitai Bot mentioned this pull request Jun 24, 2026
11 tasks
salem-2007 added a commit to salem-2007/new-api that referenced this pull request Sep 10, 2026
Add stripe support and fix wrong top up loading state
junjundesk pushed a commit to junjundesk/new-api that referenced this pull request Oct 3, 2026
Add stripe support and fix wrong top up loading state
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.

3 participants