Repository navigation
Add stripe support and fix wrong top up loading state - #1352
Conversation
WalkthroughThis 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
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
Poem
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (4)
🚧 Files skipped from review as they are similar to previous changes (4)
✨ Finishing Touches
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 9
🔭 Outside diff range comments (1)
go.mod (1)
4-4: Invalid Go version directive – replace1.23.4with a minor‐only version.
go.modonly acceptsmajor.minor(e.g.go 1.23). The additional patch component will breakgocommands (go: malformed go version).-go 1.23.4 +go 1.23
🧹 Nitpick comments (6)
common/hash.go (2)
16-20: Redundant conversion & naming mismatch inSha1Raw.
datais already[]byte;[]byte(data)allocates for no reason. Also, the pairSha256Raw(string)vsSha1Raw([]byte)is asymmetric (see previous comment).- h.Write([]byte(data)) + h.Write(data)
26-34: Minor: avoid repetitive byte slicing inside HMAC helper.
HmacSha256currently 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 importThe
verifyJSONfunction 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 renderingThe 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
⛔ Files ignored due to path filters (1)
go.sumis 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.modis up-to-dateI ran
go mod tidyand confirmed there are no unstaged changes in bothgo.modandgo.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 patternsThe 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 exposureThe 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 implementationThe 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 implementationThe
Rechargefunction implements a well-designed transactional flow with:
- Proper concurrency control using
FOR UPDATElock- 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 measuresThe 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 creationThe function properly validates the API key format and handles both existing and new customer scenarios correctly.
| var StripeApiSecret = "" | ||
| var StripeWebhookSecret = "" | ||
| var StripePriceId = "" | ||
| var StripeUnitPrice = 8.0 | ||
| var StripeMinTopUp = 1 |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Store secrets outside the binary & avoid float price.
- Hard-coding
StripeApiSecret/StripeWebhookSecretleaks credentials when logs or panic dumps print globals. Prefer env vars or an encrypted config source. - Monetary values should use integer cents or
decimal.Decimal, notfloat64, 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.
| 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.
There was a problem hiding this comment.
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
📒 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 oflocation.hrefproperly 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
enableStripeTopUpinstead ofenableOnlineTopUp, which properly controls the input state based on Stripe availability.
Add stripe support and fix wrong top up loading state
…oad-oauth-scope Feat/add file upload oauth scope
Add stripe support and fix wrong top up loading state
Add stripe support and fix wrong top up loading state
Summary by CodeRabbit
New Features
Enhancements
Chores