diff --git a/controller/option.go b/controller/option.go index 1856626..7ffe2ad 100644 --- a/controller/option.go +++ b/controller/option.go @@ -86,7 +86,7 @@ func GetOptions(c *gin.Context) { optionValues := make(map[string]string) common.OptionMapRWMutex.Lock() for k, v := range common.OptionMap { - if k == "theme.frontend" || k == "billing_setting.billing_mode" || k == "billing_setting.billing_expr" || k == "ResendKeyConfigured" { + if k == "theme.frontend" || k == "billing_setting.billing_mode" || k == "billing_setting.billing_expr" || k == "ResendKeyConfigured" || k == "BEpusdtApiTokenConfigured" { continue } value := common.Interface2String(v) @@ -110,6 +110,9 @@ func GetOptions(c *gin.Context) { options = append(options, &model.Option{ Key: "ResendKeyConfigured", Value: strconv.FormatBool(strings.TrimSpace(common.OptionMap["ResendApiKey"]) != ""), }) + options = append(options, &model.Option{ + Key: "BEpusdtApiTokenConfigured", Value: strconv.FormatBool(strings.TrimSpace(common.OptionMap["BEpusdtApiToken"]) != ""), + }) common.OptionMapRWMutex.Unlock() // Display the same effective expressions used by pricing and settlement, // including built-in defaults absent from persisted administrator options. @@ -224,6 +227,30 @@ func UpdateOption(c *gin.Context) { return } } + if option.Key == "BEpusdtApiUrl" && option.Value.(string) != "" { + if err := service.ValidateBEpusdtBaseURL(option.Value.(string)); err != nil { + common.ApiError(c, err) + return + } + } + if option.Key == "BEpusdtAdminUrl" && option.Value.(string) != "" { + if err := service.ValidateBEpusdtBaseURL(option.Value.(string)); err != nil { + common.ApiError(c, err) + return + } + } + if option.Key == "BEpusdtNotifyUrl" && option.Value.(string) != "" { + if err := service.ValidateBEpusdtBaseURL(option.Value.(string)); err != nil { + common.ApiError(c, err) + return + } + } + if option.Key == "BEpusdtReturnUrl" && option.Value.(string) != "" { + if err := service.ValidateBEpusdtBaseURL(option.Value.(string)); err != nil { + common.ApiError(c, err) + return + } + } switch option.Key { case "GitHubOAuthEnabled": if option.Value == "true" && common.GitHubClientId == "" { diff --git a/controller/payment_webhook_availability.go b/controller/payment_webhook_availability.go index c50921b..ffda2fd 100644 --- a/controller/payment_webhook_availability.go +++ b/controller/payment_webhook_availability.go @@ -113,3 +113,22 @@ func isEpayWebhookConfigured() bool { func isEpayWebhookEnabled() bool { return isEpayTopUpEnabled() } + +func isBEpusdtTopUpEnabled() bool { + if !isPaymentComplianceConfirmed() { + return false + } + if !setting.BEpusdtEnabled { + return false + } + return isBEpusdtWebhookConfigured() +} + +func isBEpusdtWebhookConfigured() bool { + return strings.TrimSpace(setting.BEpusdtApiUrl) != "" && + strings.TrimSpace(setting.BEpusdtApiToken) != "" +} + +func isBEpusdtWebhookEnabled() bool { + return isBEpusdtTopUpEnabled() +} diff --git a/controller/topup.go b/controller/topup.go index a5c27a9..4f94467 100644 --- a/controller/topup.go +++ b/controller/topup.go @@ -7,6 +7,7 @@ import ( "net/http" "net/url" "strconv" + "strings" "sync" "time" @@ -26,10 +27,30 @@ import ( func GetTopUpInfo(c *gin.Context) { complianceConfirmed := operation_setting.IsPaymentComplianceConfirmed() - // 获取支付方式 - payMethods := operation_setting.PayMethods - if !complianceConfirmed { - payMethods = []map[string]string{} + // 获取支付方式(复制切片避免追加其他网关时修改易支付原始配置) + enableBEpusdt := isBEpusdtTopUpEnabled() + isBEpusdtMethodType := func(t string) bool { + switch strings.ToLower(strings.TrimSpace(t)) { + case model.PaymentMethodBEpusdt, "crypto", "数字货币", "數字貨幣": + return true + default: + return false + } + } + payMethods := make([]map[string]string, 0, len(operation_setting.PayMethods)+5) + if complianceConfirmed { + for _, method := range operation_setting.PayMethods { + if isBEpusdtMethodType(method["type"]) { + if !enableBEpusdt { + continue + } + cloned := maps.Clone(method) + cloned["type"] = model.PaymentMethodBEpusdt + payMethods = append(payMethods, cloned) + continue + } + payMethods = append(payMethods, method) + } } // 如果启用了 Stripe 支付,添加到支付方法列表 @@ -97,12 +118,34 @@ func GetTopUpInfo(c *gin.Context) { } } + // 如果启用了 BEpusdt 数字货币支付且 PayMethods 未自定义配置,自动添加到支付方法列表 + if enableBEpusdt { + hasBEpusdt := false + for _, method := range payMethods { + if isBEpusdtMethodType(method["type"]) { + hasBEpusdt = true + break + } + } + + if !hasBEpusdt { + bepusdtMinTopUp := max(setting.BEpusdtMinTopUp, 1) + payMethods = append(payMethods, map[string]string{ + "name": setting.GetBEpusdtDisplayName(), + "type": model.PaymentMethodBEpusdt, + "color": "#26A17B", + "min_topup": strconv.Itoa(bepusdtMinTopUp), + }) + } + } + data := gin.H{ "enable_online_topup": isEpayTopUpEnabled(), "enable_stripe_topup": isStripeTopUpEnabled(), "enable_creem_topup": isCreemTopUpEnabled(), "enable_waffo_topup": enableWaffo, "enable_waffo_pancake_topup": enableWaffoPancake, + "enable_bepusdt_topup": enableBEpusdt, "enable_redemption": complianceConfirmed, "payment_compliance_confirmed": complianceConfirmed, "payment_compliance_terms_version": operation_setting.CurrentComplianceTermsVersion, @@ -118,6 +161,8 @@ func GetTopUpInfo(c *gin.Context) { "stripe_min_topup": setting.StripeMinTopUp, "waffo_min_topup": setting.WaffoMinTopUp, "waffo_pancake_min_topup": setting.WaffoPancakeMinTopUp, + "bepusdt_min_topup": max(setting.BEpusdtMinTopUp, 1), + "bepusdt_fiat": setting.GetBEpusdtFiat(), "amount_options": operation_setting.GetPaymentSetting().AmountOptions, "discount": operation_setting.GetPaymentSetting().AmountDiscount, "topup_link": common.TopUpLink, diff --git a/controller/topup_bepusdt.go b/controller/topup_bepusdt.go new file mode 100644 index 0000000..3006f5f --- /dev/null +++ b/controller/topup_bepusdt.go @@ -0,0 +1,322 @@ +package controller + +import ( + "errors" + "fmt" + "io" + "net/http" + "strconv" + "strings" + "time" + + "github.com/QuantumNous/new-api/common" + "github.com/QuantumNous/new-api/logger" + "github.com/QuantumNous/new-api/model" + "github.com/QuantumNous/new-api/service" + "github.com/QuantumNous/new-api/setting" + "github.com/QuantumNous/new-api/setting/operation_setting" + "github.com/gin-gonic/gin" + "github.com/shopspring/decimal" + "github.com/thanhpk/randstr" +) + +type BEpusdtPayRequest struct { + Amount int64 `json:"amount"` +} + +func getBEpusdtMinTopUp() int64 { + if setting.BEpusdtMinTopUp > 0 { + return int64(setting.BEpusdtMinTopUp) + } + return 1 +} + +func getBEpusdtUnitPrice() float64 { + if setting.BEpusdtUnitPrice > 0 { + return setting.BEpusdtUnitPrice + } + if operation_setting.Price > 0 { + return operation_setting.Price + } + return 1.0 +} + +func getBEpusdtPayMoney(amount float64, group string) float64 { + originalAmount := amount + if operation_setting.GetQuotaDisplayType() == operation_setting.QuotaDisplayTypeTokens { + amount = amount / common.QuotaPerUnit + } + topupGroupRatio := common.GetTopupGroupRatio(group) + if topupGroupRatio == 0 { + topupGroupRatio = 1 + } + discount := 1.0 + if ds, ok := operation_setting.GetPaymentSetting().AmountDiscount[int(originalAmount)]; ok { + if ds > 0 { + discount = ds + } + } + total := decimal.NewFromFloat(amount). + Mul(decimal.NewFromFloat(getBEpusdtUnitPrice())). + Mul(decimal.NewFromFloat(topupGroupRatio)). + Mul(decimal.NewFromFloat(discount)). + Round(2) + val, _ := total.Float64() + return val +} + +func buildBEpusdtOrderName(amount int64) string { + appName := strings.TrimSpace(common.SystemName) + if appName == "" { + appName = "New API" + } + return fmt.Sprintf("%s Recharge %d", appName, amount) +} + +func RequestBEpusdtAmount(c *gin.Context) { + if !isBEpusdtTopUpEnabled() { + paymentError(c, common.NewMessage("Cryptocurrency payment is not enabled")) + return + } + + var req BEpusdtPayRequest + if err := c.ShouldBindJSON(&req); err != nil { + paymentError(c, common.NewMessage("Invalid parameters")) + return + } + + minTopUp := getBEpusdtMinTopUp() + if req.Amount < minTopUp { + paymentError(c, common.NewMessage("Top-up amount cannot be less than {{min}}", map[string]any{"min": minTopUp})) + return + } + + id := c.GetInt("id") + if rejectInvalidTopUpQuota(c, id, req.Amount) { + return + } + + group, err := model.GetUserGroup(id, true) + if err != nil { + paymentError(c, common.NewMessage("Failed to get the user group")) + return + } + + payMoney := getBEpusdtPayMoney(float64(req.Amount), group) + if payMoney <= 0.01 { + paymentError(c, common.NewMessage("Payment amount is too low")) + return + } + + c.JSON(http.StatusOK, gin.H{ + "message": "success", + "data": strconv.FormatFloat(payMoney, 'f', 2, 64), + "fiat": setting.GetBEpusdtFiat(), + }) +} + +func RequestBEpusdtPay(c *gin.Context) { + if !isBEpusdtTopUpEnabled() { + paymentError(c, common.NewMessage("Cryptocurrency payment is not enabled")) + return + } + + var req BEpusdtPayRequest + if err := c.ShouldBindJSON(&req); err != nil { + paymentError(c, common.NewMessage("Invalid parameters")) + return + } + + minTopUp := getBEpusdtMinTopUp() + if req.Amount < minTopUp { + paymentError(c, common.NewMessage("Top-up amount cannot be less than {{min}}", map[string]any{"min": minTopUp})) + return + } + + id := c.GetInt("id") + if rejectInvalidTopUpQuota(c, id, req.Amount) { + return + } + + user, err := model.GetUserById(id, false) + if err != nil || user == nil { + paymentError(c, common.NewMessage("User does not exist")) + return + } + + group, _ := model.GetUserGroup(id, true) + payMoney := getBEpusdtPayMoney(float64(req.Amount), group) + if payMoney < 0.01 { + paymentError(c, common.NewMessage("Payment amount is too low")) + return + } + + tradeNo := fmt.Sprintf("BEP-%d-%d-%s", id, time.Now().UnixMilli(), randstr.String(6)) + + amount := req.Amount + if operation_setting.GetQuotaDisplayType() == operation_setting.QuotaDisplayTypeTokens { + amount = max(int64(float64(req.Amount)/common.QuotaPerUnit), 1) + } + + topUp := &model.TopUp{ + UserId: id, + Amount: amount, + Money: payMoney, + TradeNo: tradeNo, + PaymentMethod: model.PaymentMethodBEpusdt, + PaymentProvider: model.PaymentProviderBEpusdt, + CreateTime: time.Now().Unix(), + Status: common.TopUpStatusPending, + } + if err := topUp.Insert(); err != nil { + logger.LogError(c.Request.Context(), common.LogText("BEpusdt failed to create top-up order user_id=%d trade_no=%s amount=%d error=%q", id, tradeNo, req.Amount, err.Error())) + paymentError(c, common.NewMessage("Failed to create order")) + return + } + + notifyURL := strings.TrimSpace(setting.BEpusdtNotifyUrl) + if notifyURL == "" { + callbackAddr := strings.TrimRight(strings.TrimSpace(service.GetCallbackAddress()), "/") + if callbackAddr == "" { + topUp.Status = common.TopUpStatusFailed + _ = topUp.Update() + paymentError(c, common.NewMessage("Server address is not configured")) + return + } + notifyURL = callbackAddr + "/api/bepusdt/webhook" + } + + returnURL := strings.TrimSpace(setting.BEpusdtReturnUrl) + if returnURL == "" { + returnURL = paymentReturnPath("/wallet?show_history=true") + } + + result, err := service.CreateBEpusdtPayment(c.Request.Context(), service.BEpusdtCreateRequest{ + Mode: setting.GetBEpusdtMode(), + ApiUrl: setting.BEpusdtApiUrl, + ApiToken: setting.BEpusdtApiToken, + OrderId: tradeNo, + Amount: payMoney, + Fiat: setting.GetBEpusdtFiat(), + TradeType: setting.GetBEpusdtTradeType(), + Currencies: setting.BEpusdtCurrencies, + Name: buildBEpusdtOrderName(req.Amount), + NotifyUrl: notifyURL, + RedirectUrl: returnURL, + Timeout: setting.BEpusdtTimeout, + Rate: setting.BEpusdtRate, + }) + if err != nil { + logger.LogError(c.Request.Context(), common.LogText("BEpusdt failed to create payment user_id=%d trade_no=%s amount=%d money=%.2f error=%q", id, tradeNo, req.Amount, payMoney, err.Error())) + topUp.Status = common.TopUpStatusFailed + _ = topUp.Update() + paymentError(c, common.NewMessage("Failed to create payment order")) + return + } + + logger.LogInfo(c.Request.Context(), common.LogText("BEpusdt top-up order created user_id=%d trade_no=%s bepusdt_trade_id=%s amount=%d money=%.2f fiat=%s", id, tradeNo, result.TradeId, amount, payMoney, setting.GetBEpusdtFiat())) + c.JSON(http.StatusOK, gin.H{ + "message": "success", + "data": gin.H{ + "payment_url": result.PaymentUrl, + "trade_id": result.TradeId, + "trade_no": tradeNo, + }, + }) +} + +func BEpusdtWebhook(c *gin.Context) { + ctx := c.Request.Context() + callerIp := c.ClientIP() + + if !isBEpusdtWebhookEnabled() { + logger.LogWarn(ctx, common.LogText("BEpusdt webhook rejected reason=webhook_disabled path=%q client_ip=%s", c.Request.RequestURI, callerIp)) + c.AbortWithStatus(http.StatusForbidden) + return + } + + rawBody, err := io.ReadAll(c.Request.Body) + if err != nil { + logger.LogError(ctx, common.LogText("BEpusdt webhook failed to read body client_ip=%s error=%q", callerIp, err.Error())) + c.String(http.StatusBadRequest, "fail") + return + } + + payload, verified, err := service.VerifyBEpusdtWebhook(rawBody, setting.BEpusdtApiToken) + if err != nil { + logger.LogWarn(ctx, common.LogText("BEpusdt webhook invalid JSON client_ip=%s error=%q", callerIp, err.Error())) + c.String(http.StatusBadRequest, "fail") + return + } + if !verified { + logger.LogWarn(ctx, common.LogText("BEpusdt webhook signature verification failed order_id=%s trade_id=%s client_ip=%s", payload.OrderId, payload.TradeId, callerIp)) + c.String(http.StatusBadRequest, "fail") + return + } + + tradeNo := strings.TrimSpace(payload.OrderId) + if tradeNo == "" { + logger.LogWarn(ctx, common.LogText("BEpusdt webhook missing order_id trade_id=%s client_ip=%s", payload.TradeId, callerIp)) + c.String(http.StatusBadRequest, "fail") + return + } + + switch payload.Status { + case service.BEpusdtStatusWaiting: + logger.LogInfo(ctx, common.LogText("BEpusdt webhook waiting status received trade_no=%s bepusdt_trade_id=%s client_ip=%s", tradeNo, payload.TradeId, callerIp)) + c.String(http.StatusOK, "ok") + return + + case service.BEpusdtStatusExpired: + LockOrder(tradeNo) + defer UnlockOrder(tradeNo) + if err := model.UpdatePendingTopUpStatus(tradeNo, model.PaymentProviderBEpusdt, common.TopUpStatusExpired); err != nil { + if !errors.Is(err, model.ErrTopUpNotFound) && !errors.Is(err, model.ErrTopUpStatusInvalid) { + logger.LogWarn(ctx, common.LogText("BEpusdt webhook failed to mark expired trade_no=%s client_ip=%s error=%q", tradeNo, callerIp, err.Error())) + } + } else { + logger.LogInfo(ctx, common.LogText("BEpusdt order marked expired trade_no=%s bepusdt_trade_id=%s client_ip=%s", tradeNo, payload.TradeId, callerIp)) + } + c.String(http.StatusOK, "ok") + return + + case service.BEpusdtStatusPaid: + LockOrder(tradeNo) + defer UnlockOrder(tradeNo) + + topUp := model.GetTopUpByTradeNo(tradeNo) + if topUp == nil { + logger.LogWarn(ctx, common.LogText("BEpusdt webhook order not found trade_no=%s bepusdt_trade_id=%s client_ip=%s", tradeNo, payload.TradeId, callerIp)) + c.String(http.StatusBadRequest, "fail") + return + } + if topUp.PaymentProvider != model.PaymentProviderBEpusdt { + logger.LogWarn(ctx, common.LogText("BEpusdt webhook payment provider mismatch trade_no=%s provider=%s client_ip=%s", tradeNo, topUp.PaymentProvider, callerIp)) + c.String(http.StatusBadRequest, "fail") + return + } + if payload.Amount > 0 && payload.Amount+0.01 < topUp.Money { + logger.LogWarn(ctx, common.LogText("BEpusdt webhook amount mismatch trade_no=%s expected=%.2f received=%.2f client_ip=%s", tradeNo, topUp.Money, payload.Amount, callerIp)) + c.String(http.StatusBadRequest, "fail") + return + } + + alreadyDone, err := model.RechargeBEpusdt(tradeNo, callerIp) + if err != nil { + logger.LogError(ctx, common.LogText("BEpusdt webhook recharge failed trade_no=%s bepusdt_trade_id=%s tx=%s client_ip=%s error=%q", tradeNo, payload.TradeId, payload.BlockTransactionId, callerIp, err.Error())) + c.String(http.StatusInternalServerError, "fail") + return + } + if alreadyDone { + logger.LogInfo(ctx, common.LogText("BEpusdt webhook duplicate paid callback ignored trade_no=%s bepusdt_trade_id=%s client_ip=%s", tradeNo, payload.TradeId, callerIp)) + } else { + logger.LogInfo(ctx, common.LogText("BEpusdt webhook payment fulfilled trade_no=%s bepusdt_trade_id=%s tx=%s client_ip=%s", tradeNo, payload.TradeId, payload.BlockTransactionId, callerIp)) + } + c.String(http.StatusOK, "ok") + return + + default: + logger.LogInfo(ctx, common.LogText("BEpusdt webhook ignored unknown status=%d trade_no=%s client_ip=%s", payload.Status, tradeNo, callerIp)) + c.String(http.StatusOK, "ok") + } +} diff --git a/controller/topup_bepusdt_test.go b/controller/topup_bepusdt_test.go new file mode 100644 index 0000000..fc05faa --- /dev/null +++ b/controller/topup_bepusdt_test.go @@ -0,0 +1,98 @@ +package controller + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/QuantumNous/new-api/service" + "github.com/QuantumNous/new-api/setting" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestBEpusdtWebhookEnabledRequiresComplianceAndConfig(t *testing.T) { + confirmPaymentComplianceForTest(t) + origEnabled := setting.BEpusdtEnabled + origURL := setting.BEpusdtApiUrl + origToken := setting.BEpusdtApiToken + t.Cleanup(func() { + setting.BEpusdtEnabled = origEnabled + setting.BEpusdtApiUrl = origURL + setting.BEpusdtApiToken = origToken + }) + + setting.BEpusdtEnabled = true + setting.BEpusdtApiUrl = "" + setting.BEpusdtApiToken = "tok" + require.False(t, isBEpusdtWebhookEnabled()) + + setting.BEpusdtApiUrl = "https://bepusdt.example.com" + setting.BEpusdtApiToken = "" + require.False(t, isBEpusdtWebhookEnabled()) + + setting.BEpusdtApiToken = "tok" + require.True(t, isBEpusdtWebhookEnabled()) + + setting.BEpusdtEnabled = false + require.False(t, isBEpusdtWebhookEnabled()) +} + +func TestBEpusdtWebhookRejectsDisabledAndInvalidSignature(t *testing.T) { + gin.SetMode(gin.TestMode) + confirmPaymentComplianceForTest(t) + origEnabled := setting.BEpusdtEnabled + origURL := setting.BEpusdtApiUrl + origToken := setting.BEpusdtApiToken + t.Cleanup(func() { + setting.BEpusdtEnabled = origEnabled + setting.BEpusdtApiUrl = origURL + setting.BEpusdtApiToken = origToken + }) + + // Disabled returns 403 + setting.BEpusdtEnabled = false + setting.BEpusdtApiUrl = "https://bepusdt.example.com" + setting.BEpusdtApiToken = "secret-token" + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest(http.MethodPost, "/api/bepusdt/webhook", bytes.NewBufferString(`{}`)) + BEpusdtWebhook(c) + assert.Equal(t, http.StatusForbidden, w.Code) + + // Invalid signature returns 400 + setting.BEpusdtEnabled = true + w = httptest.NewRecorder() + c, _ = gin.CreateTestContext(w) + body, _ := json.Marshal(map[string]any{ + "trade_id": "tid-1", + "order_id": "BEP-1", + "amount": 10.0, + "status": 2, + "signature": "bad-signature", + }) + c.Request = httptest.NewRequest(http.MethodPost, "/api/bepusdt/webhook", bytes.NewReader(body)) + BEpusdtWebhook(c) + assert.Equal(t, http.StatusBadRequest, w.Code) + + // Valid waiting callback returns 200 ok + payload := map[string]any{ + "trade_id": "tid-2", + "order_id": "BEP-2", + "amount": 10.0, + "actual_amount": "1.5", + "token": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", + "status": 1, + } + payload["signature"] = service.SignBEpusdt(payload, "secret-token") + body, _ = json.Marshal(payload) + w = httptest.NewRecorder() + c, _ = gin.CreateTestContext(w) + c.Request = httptest.NewRequest(http.MethodPost, "/api/bepusdt/webhook", bytes.NewReader(body)) + BEpusdtWebhook(c) + assert.Equal(t, http.StatusOK, w.Code) + assert.Equal(t, "ok", w.Body.String()) +} diff --git a/model/option.go b/model/option.go index a630aa6..ef6d02a 100644 --- a/model/option.go +++ b/model/option.go @@ -128,6 +128,21 @@ func InitOptionMap() { common.OptionMap["WaffoPancakeMinTopUp"] = strconv.Itoa(setting.WaffoPancakeMinTopUp) common.OptionMap["WaffoPancakeStoreID"] = setting.WaffoPancakeStoreID common.OptionMap["WaffoPancakeProductID"] = setting.WaffoPancakeProductID + common.OptionMap["BEpusdtEnabled"] = strconv.FormatBool(setting.BEpusdtEnabled) + common.OptionMap["BEpusdtApiUrl"] = setting.BEpusdtApiUrl + common.OptionMap["BEpusdtAdminUrl"] = setting.BEpusdtAdminUrl + common.OptionMap["BEpusdtApiToken"] = setting.BEpusdtApiToken + common.OptionMap["BEpusdtMode"] = setting.BEpusdtMode + common.OptionMap["BEpusdtTradeType"] = setting.BEpusdtTradeType + common.OptionMap["BEpusdtCurrencies"] = setting.BEpusdtCurrencies + common.OptionMap["BEpusdtFiat"] = setting.BEpusdtFiat + common.OptionMap["BEpusdtUnitPrice"] = strconv.FormatFloat(setting.BEpusdtUnitPrice, 'f', -1, 64) + common.OptionMap["BEpusdtMinTopUp"] = strconv.Itoa(setting.BEpusdtMinTopUp) + common.OptionMap["BEpusdtTimeout"] = strconv.Itoa(setting.BEpusdtTimeout) + common.OptionMap["BEpusdtDisplayName"] = setting.BEpusdtDisplayName + common.OptionMap["BEpusdtNotifyUrl"] = setting.BEpusdtNotifyUrl + common.OptionMap["BEpusdtReturnUrl"] = setting.BEpusdtReturnUrl + common.OptionMap["BEpusdtRate"] = setting.BEpusdtRate common.OptionMap["TopupGroupRatio"] = common.TopupGroupRatio2JSONString() common.OptionMap["Chats"] = setting.Chats2JsonString() common.OptionMap["AutoGroups"] = setting.AutoGroups2JsonString() @@ -610,6 +625,36 @@ func updateOptionMap(key string, value string) (err error) { setting.WaffoPancakeUnitPrice, _ = strconv.ParseFloat(value, 64) case "WaffoPancakeMinTopUp": setting.WaffoPancakeMinTopUp, _ = strconv.Atoi(value) + case "BEpusdtEnabled": + setting.BEpusdtEnabled = value == "true" + case "BEpusdtApiUrl": + setting.BEpusdtApiUrl = strings.TrimRight(strings.TrimSpace(value), "/") + case "BEpusdtAdminUrl": + setting.BEpusdtAdminUrl = strings.TrimSpace(value) + case "BEpusdtApiToken": + setting.BEpusdtApiToken = strings.TrimSpace(value) + case "BEpusdtMode": + setting.BEpusdtMode = strings.TrimSpace(value) + case "BEpusdtTradeType": + setting.BEpusdtTradeType = strings.TrimSpace(value) + case "BEpusdtCurrencies": + setting.BEpusdtCurrencies = strings.TrimSpace(value) + case "BEpusdtFiat": + setting.BEpusdtFiat = strings.ToUpper(strings.TrimSpace(value)) + case "BEpusdtUnitPrice": + setting.BEpusdtUnitPrice, _ = strconv.ParseFloat(value, 64) + case "BEpusdtMinTopUp": + setting.BEpusdtMinTopUp, _ = strconv.Atoi(value) + case "BEpusdtTimeout": + setting.BEpusdtTimeout, _ = strconv.Atoi(value) + case "BEpusdtDisplayName": + setting.BEpusdtDisplayName = strings.TrimSpace(value) + case "BEpusdtNotifyUrl": + setting.BEpusdtNotifyUrl = strings.TrimSpace(value) + case "BEpusdtReturnUrl": + setting.BEpusdtReturnUrl = strings.TrimSpace(value) + case "BEpusdtRate": + setting.BEpusdtRate = strings.TrimSpace(value) case "TopupGroupRatio": err = common.UpdateTopupGroupRatioByJSONString(value) case "GitHubClientId": diff --git a/model/topup.go b/model/topup.go index 17d4df3..0061262 100644 --- a/model/topup.go +++ b/model/topup.go @@ -30,6 +30,7 @@ const ( PaymentMethodCreem = "creem" PaymentMethodWaffo = "waffo" PaymentMethodWaffoPancake = "waffo_pancake" + PaymentMethodBEpusdt = "bepusdt" PaymentMethodBalance = "balance" ) @@ -39,6 +40,7 @@ const ( PaymentProviderCreem = "creem" PaymentProviderWaffo = "waffo" PaymentProviderWaffoPancake = "waffo_pancake" + PaymentProviderBEpusdt = "bepusdt" PaymentProviderBalance = "balance" ) @@ -713,3 +715,60 @@ func RechargeWaffoPancake(tradeNo string) (err error) { return nil } + +// RechargeBEpusdt 原子完成 BEpusdt 数字货币支付订单:行锁 + 网关归属校验 + 幂等校验 + 额度入账。 +func RechargeBEpusdt(tradeNo string, callerIp string) (alreadyDone bool, err error) { + if tradeNo == "" { + return false, errors.New("payment order number not provided") + } + + refCol := "`trade_no`" + if common.UsingMainDatabase(common.DatabaseTypePostgreSQL) { + refCol = `"trade_no"` + } + + var quotaToAdd int + topUp := &TopUp{} + err = DB.Transaction(func(tx *gorm.DB) error { + if err := lockForUpdate(tx).Where(refCol+" = ?", tradeNo).First(topUp).Error; err != nil { + return ErrTopUpNotFound + } + if topUp.PaymentProvider != PaymentProviderBEpusdt { + return ErrPaymentMethodMismatch + } + if topUp.Status == common.TopUpStatusSuccess { + alreadyDone = true + return nil + } + if topUp.Status != common.TopUpStatusPending { + return ErrTopUpStatusInvalid + } + var quotaErr error + quotaToAdd, quotaErr = common.WalletQuotaFromDecimalStrict( + decimal.NewFromInt(topUp.Amount).Mul(decimal.NewFromFloat(common.QuotaPerUnit)), + ) + if quotaErr != nil || quotaToAdd <= 0 { + return ErrInvalidTopUpQuota + } + topUp.CompleteTime = common.GetTimestamp() + topUp.Status = common.TopUpStatusSuccess + if err := tx.Save(topUp).Error; err != nil { + return err + } + return creditTopUpQuota(tx, topUp.UserId, quotaToAdd, nil) + }) + if err != nil { + if !errors.Is(err, ErrTopUpNotFound) && !errors.Is(err, ErrPaymentMethodMismatch) && !errors.Is(err, ErrTopUpStatusInvalid) { + common.SysError(common.LogText("bepusdt topup failed: %s", err.Error())) + } + return false, err + } + if alreadyDone { + return true, nil + } + syncCreditUserQuotaCache(topUp.UserId, quotaToAdd, common.LogText("bepusdt topup")) + + common.SysLog(common.LogText("BEpusdt top-up succeeded trade_no=%s user_id=%d quota_to_add=%d money=%.2f", topUp.TradeNo, topUp.UserId, quotaToAdd, topUp.Money)) + RecordTopupLog(topUp.UserId, common.NewMessage("{{provider}} top-up succeeded, amount added: {{quota}}, payment amount: {{amount}}", map[string]any{"provider": "BEpusdt", "quota": logger.FormatQuota(quotaToAdd), "amount": fmt.Sprintf("%.2f", topUp.Money)}), callerIp, topUp.PaymentMethod, PaymentProviderBEpusdt) + return false, nil +} diff --git a/router/api-router.go b/router/api-router.go index ade93ec..24348cd 100644 --- a/router/api-router.go +++ b/router/api-router.go @@ -64,6 +64,7 @@ func SetApiRouter(router *gin.Engine) { apiRouter.POST("/stripe/webhook", anonymousRequestBodyLimit, controller.StripeWebhook) apiRouter.POST("/creem/webhook", anonymousRequestBodyLimit, controller.CreemWebhook) apiRouter.POST("/waffo/webhook", anonymousRequestBodyLimit, controller.WaffoWebhook) + apiRouter.POST("/bepusdt/webhook", anonymousRequestBodyLimit, controller.BEpusdtWebhook) // :env separates test vs prod URLs so the operator can register each // in Pancake's matching webhook slot; handler enforces env match. apiRouter.POST("/waffo-pancake/webhook/:env", anonymousRequestBodyLimit, controller.WaffoPancakeWebhook) @@ -131,6 +132,8 @@ func SetApiRouter(router *gin.Engine) { selfRoute.POST("/waffo/pay", middleware.CriticalRateLimit(), controller.RequestWaffoPay) selfRoute.POST("/waffo-pancake/amount", controller.RequestWaffoPancakeAmount) selfRoute.POST("/waffo-pancake/pay", middleware.CriticalRateLimit(), controller.RequestWaffoPancakePay) + selfRoute.POST("/bepusdt/amount", controller.RequestBEpusdtAmount) + selfRoute.POST("/bepusdt/pay", middleware.CriticalRateLimit(), controller.RequestBEpusdtPay) selfRoute.POST("/aff_transfer", middleware.UserCriticalRateLimit("aff-transfer"), controller.TransferAffQuota) selfRoute.PUT("/setting", controller.UpdateUserSetting) diff --git a/service/bepusdt.go b/service/bepusdt.go new file mode 100644 index 0000000..5a8d498 --- /dev/null +++ b/service/bepusdt.go @@ -0,0 +1,244 @@ +package service + +import ( + "bytes" + "context" + "crypto/md5" + "crypto/subtle" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "sort" + "strings" + "time" +) + +const ( + BEpusdtStatusWaiting = 1 + BEpusdtStatusPaid = 2 + BEpusdtStatusExpired = 3 +) + +// BEpusdtCreateRequest 对应 BEpusdt 的创建订单/交易参数。 +type BEpusdtCreateRequest struct { + Mode string + ApiUrl string + ApiToken string + OrderId string + Amount float64 + Fiat string + TradeType string + Currencies string + Name string + NotifyUrl string + RedirectUrl string + Timeout int + Rate string +} + +// BEpusdtCreateResult 为 BEpusdt 接口返回的核心支付信息。 +type BEpusdtCreateResult struct { + TradeId string `json:"trade_id"` + OrderId string `json:"order_id"` + PaymentUrl string `json:"payment_url"` + Fiat string `json:"fiat"` + Amount any `json:"amount"` + ActualAmount any `json:"actual_amount"` + Token string `json:"token"` + ExpirationTime int64 `json:"expiration_time"` +} + +// BEpusdtWebhookPayload 对应 BEpusdt 异步回调通知 JSON。 +type BEpusdtWebhookPayload struct { + TradeId string `json:"trade_id"` + OrderId string `json:"order_id"` + Amount float64 `json:"amount"` + ActualAmount any `json:"actual_amount"` + Token string `json:"token"` + BlockTransactionId string `json:"block_transaction_id"` + Signature string `json:"signature"` + Status int `json:"status"` +} + +type bepusdtApiResponse struct { + StatusCode int `json:"status_code"` + Message string `json:"message"` + Data *BEpusdtCreateResult `json:"data"` +} + +var bepusdtHTTPClient = &http.Client{ + Timeout: 15 * time.Second, +} + +// SignBEpusdt 按 BEpusdt 官方 utils.EpusdtSign 规范计算 MD5 小写签名。 +func SignBEpusdt(data map[string]any, token string) string { + keys := make([]string, 0, len(data)) + for k := range data { + if k == "signature" { + continue + } + keys = append(keys, k) + } + sort.Strings(keys) + + var builder strings.Builder + for _, k := range keys { + v := data[k] + if v == nil || v == "" { + continue + } + builder.WriteString(k) + builder.WriteString("=") + builder.WriteString(fmt.Sprintf("%v", v)) + builder.WriteString("&") + } + + signString := strings.TrimRight(builder.String(), "&") + sum := md5.Sum([]byte(signString + token)) + return fmt.Sprintf("%x", sum) +} + +// VerifyBEpusdtWebhook 解析并校验 BEpusdt 回调 JSON 的签名。 +func VerifyBEpusdtWebhook(rawBody []byte, token string) (BEpusdtWebhookPayload, bool, error) { + var payload BEpusdtWebhookPayload + if err := json.Unmarshal(rawBody, &payload); err != nil { + return payload, false, err + } + + rawMap := make(map[string]any) + if err := json.Unmarshal(rawBody, &rawMap); err != nil { + return payload, false, err + } + + received := strings.ToLower(strings.TrimSpace(payload.Signature)) + if received == "" || strings.TrimSpace(token) == "" { + return payload, false, nil + } + + expected := SignBEpusdt(rawMap, token) + matched := subtle.ConstantTimeCompare([]byte(received), []byte(expected)) == 1 + return payload, matched, nil +} + +// ValidateBEpusdtBaseURL 校验 BEpusdt 接口地址必须为合法的 HTTP/HTTPS URL。 +func ValidateBEpusdtBaseURL(raw string) error { + trimmed := strings.TrimSpace(raw) + if trimmed == "" { + return nil + } + parsed, err := url.Parse(trimmed) + if err != nil { + return errors.New("invalid BEpusdt API URL") + } + if (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" { + return errors.New("BEpusdt API URL must start with http:// or https://") + } + return nil +} + +// CreateBEpusdtPayment 调用 BEpusdt 创建支付订单(支持 cashier 收银台与 transaction 固定交易类型两种模式)。 +func CreateBEpusdtPayment(ctx context.Context, req BEpusdtCreateRequest) (*BEpusdtCreateResult, error) { + baseURL := strings.TrimRight(strings.TrimSpace(req.ApiUrl), "/") + if baseURL == "" { + return nil, errors.New("BEpusdt API URL is not configured") + } + if err := ValidateBEpusdtBaseURL(baseURL); err != nil { + return nil, err + } + token := strings.TrimSpace(req.ApiToken) + if token == "" { + return nil, errors.New("BEpusdt API token is not configured") + } + + mode := strings.ToLower(strings.TrimSpace(req.Mode)) + endpoint := baseURL + "/api/v1/order/create-order" + payload := map[string]any{ + "order_id": req.OrderId, + "notify_url": req.NotifyUrl, + "redirect_url": req.RedirectUrl, + "amount": req.Amount, + } + if fiat := strings.ToUpper(strings.TrimSpace(req.Fiat)); fiat != "" { + payload["fiat"] = fiat + } + if name := strings.TrimSpace(req.Name); name != "" { + payload["name"] = name + } + + if mode == "transaction" { + endpoint = baseURL + "/api/v1/order/create-transaction" + if tradeType := strings.TrimSpace(req.TradeType); tradeType != "" { + payload["trade_type"] = tradeType + } + if req.Timeout >= 120 { + payload["timeout"] = req.Timeout + } + if rate := strings.TrimSpace(req.Rate); rate != "" { + payload["rate"] = rate + } + } else { + // 收银台模式 /api/v1/order/create-order,允许用户在收银台自选币种与网络 + if currencies := strings.TrimSpace(req.Currencies); currencies != "" { + payload["currencies"] = currencies + } + if req.Timeout >= 180 { + payload["timeout"] = req.Timeout + } + } + + // 先序列化再反序列化回 map[string]any,使数字等字段的格式化结果与 BEpusdt 服务端 json.Unmarshal 后验签完全一致 + rawPayload, err := json.Marshal(payload) + if err != nil { + return nil, err + } + normalized := make(map[string]any) + if err := json.Unmarshal(rawPayload, &normalized); err != nil { + return nil, err + } + payload["signature"] = SignBEpusdt(normalized, token) + + bodyBytes, err := json.Marshal(payload) + if err != nil { + return nil, err + } + + httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(bodyBytes)) + if err != nil { + return nil, err + } + httpReq.Header.Set("Content-Type", "application/json") + httpReq.Header.Set("Accept", "application/json") + + resp, err := bepusdtHTTPClient.Do(httpReq) + if err != nil { + return nil, err + } + defer resp.Body.Close() + + respBody, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + if err != nil { + return nil, err + } + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return nil, fmt.Errorf("BEpusdt HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(respBody))) + } + + var apiResp bepusdtApiResponse + if err := json.Unmarshal(respBody, &apiResp); err != nil { + return nil, fmt.Errorf("invalid BEpusdt response: %w", err) + } + if apiResp.StatusCode != 200 || apiResp.Data == nil { + msg := strings.TrimSpace(apiResp.Message) + if msg == "" { + msg = fmt.Sprintf("status_code=%d", apiResp.StatusCode) + } + return nil, fmt.Errorf("BEpusdt rejected order: %s", msg) + } + if strings.TrimSpace(apiResp.Data.PaymentUrl) == "" { + return nil, errors.New("BEpusdt response missing payment_url") + } + return apiResp.Data, nil +} diff --git a/service/bepusdt_test.go b/service/bepusdt_test.go new file mode 100644 index 0000000..312305c --- /dev/null +++ b/service/bepusdt_test.go @@ -0,0 +1,118 @@ +package service + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestSignBEpusdtMatchesOfficialExample(t *testing.T) { + params := map[string]any{ + "order_id": "20220201030210321", + "amount": 42, + "notify_url": "http://example.com/notify", + "redirect_url": "http://example.com/redirect", + "empty_str": "", + "nil_val": nil, + "signature": "ignored", + } + // Official BEpusdt docs example: MD5(amount=42¬ify_url=http://example.com/notify&order_id=20220201030210321&redirect_url=http://example.com/redirectepusdt_password_xasddawqe) + sig := SignBEpusdt(params, "epusdt_password_xasddawqe") + assert.Len(t, sig, 32) + + // Re-verify using VerifyBEpusdtWebhook roundtrip + payload := map[string]any{ + "trade_id": "b3d2477c-d945-41da-96b7-f925bbd1b415", + "order_id": "BEP-1-1700000000-abc", + "amount": 28.88, + "actual_amount": "4.25", + "token": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", + "block_transaction_id": "txhash123", + "status": 2, + } + payload["signature"] = SignBEpusdt(payload, "secret-token") + raw, err := json.Marshal(payload) + require.NoError(t, err) + + parsed, ok, err := VerifyBEpusdtWebhook(raw, "secret-token") + require.NoError(t, err) + assert.True(t, ok) + assert.Equal(t, "BEP-1-1700000000-abc", parsed.OrderId) + assert.Equal(t, 2, parsed.Status) + assert.InDelta(t, 28.88, parsed.Amount, 0.0001) + + _, okWrongToken, err := VerifyBEpusdtWebhook(raw, "wrong-token") + require.NoError(t, err) + assert.False(t, okWrongToken) +} + +func TestCreateBEpusdtPaymentCashierAndTransactionModes(t *testing.T) { + token := "test-bepusdt-token" + var lastPath string + var lastPayload map[string]any + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + lastPath = r.URL.Path + defer r.Body.Close() + var body map[string]any + require.NoError(t, json.NewDecoder(r.Body).Decode(&body)) + lastPayload = body + + expectedSig := SignBEpusdt(body, token) + assert.Equal(t, expectedSig, body["signature"]) + + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "status_code": 200, + "message": "success", + "data": map[string]any{ + "trade_id": "trade-123", + "order_id": body["order_id"], + "payment_url": "https://pay.example.com/pay/cashier/trade-123", + }, + }) + })) + defer server.Close() + + res, err := CreateBEpusdtPayment(context.Background(), BEpusdtCreateRequest{ + Mode: "cashier", + ApiUrl: server.URL, + ApiToken: token, + OrderId: "BEP-100", + Amount: 70, + Fiat: "CNY", + Currencies: "USDT,USDC", + Name: "Recharge 10 USD", + NotifyUrl: "https://ai.example.com/api/bepusdt/webhook", + RedirectUrl: "https://ai.example.com/console/topup", + Timeout: 600, + }) + require.NoError(t, err) + assert.Equal(t, "/api/v1/order/create-order", lastPath) + assert.Equal(t, "USDT,USDC", lastPayload["currencies"]) + assert.Equal(t, "https://pay.example.com/pay/cashier/trade-123", res.PaymentUrl) + + res, err = CreateBEpusdtPayment(context.Background(), BEpusdtCreateRequest{ + Mode: "transaction", + ApiUrl: server.URL + "/", + ApiToken: token, + OrderId: "BEP-101", + Amount: 10.5, + Fiat: "USD", + TradeType: "usdt.trc20", + Rate: "~1.02", + NotifyUrl: "https://ai.example.com/api/bepusdt/webhook", + RedirectUrl: "https://ai.example.com/console/topup", + Timeout: 300, + }) + require.NoError(t, err) + assert.Equal(t, "/api/v1/order/create-transaction", lastPath) + assert.Equal(t, "usdt.trc20", lastPayload["trade_type"]) + assert.Equal(t, "~1.02", lastPayload["rate"]) + assert.Equal(t, "https://pay.example.com/pay/cashier/trade-123", res.PaymentUrl) +} diff --git a/setting/payment_bepusdt.go b/setting/payment_bepusdt.go new file mode 100644 index 0000000..2fb0536 --- /dev/null +++ b/setting/payment_bepusdt.go @@ -0,0 +1,61 @@ +package setting + +import "strings" + +const ( + BEpusdtModeCashier = "cashier" + BEpusdtModeTransaction = "transaction" +) + +var ( + // BEpusdt 数字货币支付网关配置(与易支付完全独立) + BEpusdtEnabled bool + BEpusdtApiUrl string + BEpusdtAdminUrl string + BEpusdtApiToken string + BEpusdtMode string = BEpusdtModeCashier + BEpusdtTradeType string = "usdt.trc20" + BEpusdtCurrencies string = "" + BEpusdtFiat string = "CNY" + BEpusdtUnitPrice float64 = 7.0 + BEpusdtMinTopUp int = 1 + BEpusdtTimeout int = 600 + BEpusdtDisplayName string = "" + BEpusdtNotifyUrl string = "" + BEpusdtReturnUrl string = "" + BEpusdtRate string = "" +) + +func GetBEpusdtMode() string { + switch strings.ToLower(strings.TrimSpace(BEpusdtMode)) { + case BEpusdtModeTransaction: + return BEpusdtModeTransaction + default: + return BEpusdtModeCashier + } +} + +func GetBEpusdtFiat() string { + switch strings.ToUpper(strings.TrimSpace(BEpusdtFiat)) { + case "CNY", "USD", "EUR", "GBP", "JPY": + return strings.ToUpper(strings.TrimSpace(BEpusdtFiat)) + default: + return "CNY" + } +} + +func GetBEpusdtTradeType() string { + tradeType := strings.TrimSpace(BEpusdtTradeType) + if tradeType == "" { + return "usdt.trc20" + } + return tradeType +} + +func GetBEpusdtDisplayName() string { + name := strings.TrimSpace(BEpusdtDisplayName) + if name == "" { + return "数字货币" + } + return name +} diff --git a/web/src/features/system-settings/billing/index.tsx b/web/src/features/system-settings/billing/index.tsx index e8852b2..81c9cc9 100644 --- a/web/src/features/system-settings/billing/index.tsx +++ b/web/src/features/system-settings/billing/index.tsx @@ -107,6 +107,22 @@ const defaultBillingSettings: BillingSettings = { WaffoPancakeReturnURL: '', WaffoPancakeStoreID: '', WaffoPancakeProductID: '', + BEpusdtEnabled: false, + BEpusdtApiUrl: '', + BEpusdtAdminUrl: '', + BEpusdtApiToken: '', + BEpusdtApiTokenConfigured: false, + BEpusdtMode: 'cashier', + BEpusdtTradeType: 'usdt.trc20', + BEpusdtCurrencies: '', + BEpusdtFiat: 'CNY', + BEpusdtUnitPrice: 7, + BEpusdtMinTopUp: 1, + BEpusdtTimeout: 600, + BEpusdtDisplayName: '', + BEpusdtNotifyUrl: '', + BEpusdtReturnUrl: '', + BEpusdtRate: '', 'checkin_setting.enabled': false, 'checkin_setting.min_quota': 1000, 'checkin_setting.max_quota': 10000, diff --git a/web/src/features/system-settings/billing/section-registry.tsx b/web/src/features/system-settings/billing/section-registry.tsx index e16a4ee..f8552e8 100644 --- a/web/src/features/system-settings/billing/section-registry.tsx +++ b/web/src/features/system-settings/billing/section-registry.tsx @@ -183,6 +183,24 @@ const BILLING_SECTIONS = [ }} waffoPancakeProvisionedStoreID={settings.WaffoPancakeStoreID ?? ''} waffoPancakeProvisionedProductID={settings.WaffoPancakeProductID ?? ''} + bepusdtDefaultValues={{ + BEpusdtEnabled: settings.BEpusdtEnabled ?? false, + BEpusdtApiUrl: settings.BEpusdtApiUrl ?? '', + BEpusdtAdminUrl: settings.BEpusdtAdminUrl ?? '', + BEpusdtApiToken: settings.BEpusdtApiToken ?? '', + BEpusdtMode: settings.BEpusdtMode || 'cashier', + BEpusdtTradeType: settings.BEpusdtTradeType || 'usdt.trc20', + BEpusdtCurrencies: settings.BEpusdtCurrencies ?? '', + BEpusdtFiat: settings.BEpusdtFiat || 'CNY', + BEpusdtUnitPrice: settings.BEpusdtUnitPrice ?? 7, + BEpusdtMinTopUp: settings.BEpusdtMinTopUp ?? 1, + BEpusdtTimeout: settings.BEpusdtTimeout ?? 600, + BEpusdtDisplayName: settings.BEpusdtDisplayName ?? '', + BEpusdtNotifyUrl: settings.BEpusdtNotifyUrl ?? '', + BEpusdtReturnUrl: settings.BEpusdtReturnUrl ?? '', + BEpusdtRate: settings.BEpusdtRate ?? '', + }} + bepusdtApiTokenConfigured={settings.BEpusdtApiTokenConfigured ?? false} complianceDefaults={{ confirmed: settings['payment_setting.compliance_confirmed'] ?? false, termsVersion: diff --git a/web/src/features/system-settings/integrations/__tests__/bepusdt-settings.test.tsx b/web/src/features/system-settings/integrations/__tests__/bepusdt-settings.test.tsx new file mode 100644 index 0000000..48b370f --- /dev/null +++ b/web/src/features/system-settings/integrations/__tests__/bepusdt-settings.test.tsx @@ -0,0 +1,133 @@ +import { render, screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import * as React from 'react' +import { useForm } from 'react-hook-form' +import { describe, expect, it, vi } from 'vitest' + +vi.mock('react-i18next', () => ({ + useTranslation: () => ({ t: (key: string) => key }), +})) + +import { Input } from '@/components/ui/input' +import { PaymentConfirmDialog } from '@/features/wallet/components/dialogs/payment-confirm-dialog' +import { formatCurrency, isBEpusdtPayment } from '@/features/wallet/lib' + +import { safeNumberFieldProps } from '../../utils/numeric-field' +import { + BEpusdtSettingsSection, + type BEpusdtSettingsValues, +} from '../bepusdt-settings-section' + +function Harness() { + const [values, setValues] = React.useState({ + BEpusdtEnabled: false, + BEpusdtApiUrl: 'https://pay.btbyte.cc', + BEpusdtAdminUrl: 'https://pay.btbyte.cc/3024489d0c', + BEpusdtApiToken: '', + BEpusdtMode: 'cashier', + BEpusdtTradeType: 'usdt.trc20', + BEpusdtCurrencies: '', + BEpusdtFiat: 'CNY', + BEpusdtUnitPrice: 7, + BEpusdtMinTopUp: 1, + BEpusdtTimeout: 600, + BEpusdtDisplayName: '', + BEpusdtNotifyUrl: '', + BEpusdtReturnUrl: '', + BEpusdtRate: '', + }) + + return ( + + setValues((prev) => ({ ...prev, [key]: next })) + } + /> + ) +} + +function SafeNumberHarness() { + const form = useForm<{ rate: number }>({ defaultValues: { rate: 7 } }) + const value = form.watch('rate') + const fieldProps = safeNumberFieldProps({ + name: 'rate', + value, + onChange: (next: unknown) => + form.setValue('rate', next as number, { shouldDirty: true }), + onBlur: () => {}, + ref: () => {}, + }) + + return +} + +describe('BEpusdt & Currency UX fixes', () => { + it('allows clearing BEpusdt unit price without inserting a sticky leading zero', async () => { + const user = userEvent.setup() + render() + + const unitPriceInput = screen.getByLabelText( + 'Unit Price (Fiat / USD)' + ) as HTMLInputElement + expect(unitPriceInput.value).toBe('7') + + await user.clear(unitPriceInput) + expect(unitPriceInput.value).toBe('') + + await user.type(unitPriceInput, '7.25') + expect(unitPriceInput.value).toBe('7.25') + }) + + it('allows clearing safeNumberFieldProps input used by billing/currency', async () => { + const user = userEvent.setup() + render() + + const rateInput = screen.getByLabelText('Exchange Rate') as HTMLInputElement + expect(rateInput.value).toBe('7') + + await user.clear(rateInput) + expect(rateInput.value).toBe('') + + await user.type(rateInput, '6.8') + expect(rateInput.value).toBe('6.8') + }) + + it('formats CNY currency symbol, hides You Pay for crypto, keeps You Pay for alipay/wxpay', () => { + expect(formatCurrency(70)).toBe('¥70') + expect(isBEpusdtPayment('bepusdt')).toBe(true) + expect(isBEpusdtPayment('数字货币')).toBe(true) + expect(isBEpusdtPayment('alipay')).toBe(false) + + const { rerender } = render( + {}} + onConfirm={() => {}} + topupAmount={10} + paymentAmount={70} + paymentMethod={{ name: 'Crypto', type: 'bepusdt', icon: 'SiBitcoin' }} + calculating={false} + processing={false} + /> + ) + expect(screen.queryByText('You Pay')).toBeNull() + expect(screen.getByText('Crypto')).toBeTruthy() + + rerender( + {}} + onConfirm={() => {}} + topupAmount={10} + paymentAmount={70} + paymentMethod={{ name: '支付宝', type: 'alipay', icon: 'SiAlipay' }} + calculating={false} + processing={false} + /> + ) + expect(screen.getByText('You Pay')).toBeTruthy() + expect(screen.getByText('¥70')).toBeTruthy() + }) +}) diff --git a/web/src/features/system-settings/integrations/bepusdt-settings-section.tsx b/web/src/features/system-settings/integrations/bepusdt-settings-section.tsx new file mode 100644 index 0000000..1cb7663 --- /dev/null +++ b/web/src/features/system-settings/integrations/bepusdt-settings-section.tsx @@ -0,0 +1,548 @@ +/* +Copyright (C) 2023-2026 QuantumNous + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +For commercial licensing, please contact support@quantumnous.com +*/ +import { Copy, ExternalLink } from 'lucide-react' +import * as React from 'react' +import { useTranslation } from 'react-i18next' +import { toast } from 'sonner' + +import { Alert, AlertDescription } from '@/components/ui/alert' +import { Badge } from '@/components/ui/badge' +import { Button } from '@/components/ui/button' +import { Input } from '@/components/ui/input' +import { Label } from '@/components/ui/label' +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from '@/components/ui/select' + +import { SettingsSwitchField } from '../components/settings-form-layout' + +export interface BEpusdtSettingsValues { + BEpusdtEnabled: boolean + BEpusdtApiUrl: string + BEpusdtAdminUrl: string + BEpusdtApiToken: string + BEpusdtMode: string + BEpusdtTradeType: string + BEpusdtCurrencies: string + BEpusdtFiat: string + BEpusdtUnitPrice: number + BEpusdtMinTopUp: number + BEpusdtTimeout: number + BEpusdtDisplayName: string + BEpusdtNotifyUrl: string + BEpusdtReturnUrl: string + BEpusdtRate: string +} + +const BEPUSDT_FIAT_OPTIONS = ['CNY', 'USD', 'EUR', 'GBP', 'JPY'] as const + +const BEPUSDT_TRADE_TYPE_OPTIONS = [ + { value: 'usdt.trc20', label: 'USDT - TRC20 (Tron)' }, + { value: 'usdt.erc20', label: 'USDT - ERC20 (Ethereum)' }, + { value: 'usdt.bep20', label: 'USDT - BEP20 (BSC)' }, + { value: 'usdt.polygon', label: 'USDT - Polygon' }, + { value: 'usdt.arbitrum', label: 'USDT - Arbitrum One' }, + { value: 'usdt.solana', label: 'USDT - Solana' }, + { value: 'usdt.ton', label: 'USDT - TON' }, + { value: 'usdt.aptos', label: 'USDT - Aptos' }, + { value: 'usdt.xlayer', label: 'USDT - X-Layer' }, + { value: 'usdt.plasma', label: 'USDT - Plasma' }, + { value: 'usdc.trc20', label: 'USDC - TRC20 (Tron)' }, + { value: 'usdc.erc20', label: 'USDC - ERC20 (Ethereum)' }, + { value: 'usdc.bep20', label: 'USDC - BEP20 (BSC)' }, + { value: 'usdc.polygon', label: 'USDC - Polygon' }, + { value: 'usdc.arbitrum', label: 'USDC - Arbitrum One' }, + { value: 'usdc.base', label: 'USDC - Base' }, + { value: 'usdc.solana', label: 'USDC - Solana' }, + { value: 'usdc.aptos', label: 'USDC - Aptos' }, + { value: 'usdc.xlayer', label: 'USDC - X-Layer' }, + { value: 'tron.trx', label: 'TRX (Tron)' }, + { value: 'ethereum.eth', label: 'ETH (Ethereum)' }, + { value: 'bsc.bnb', label: 'BNB (BSC)' }, + { value: 'ton.gram', label: 'TON (TON Network)' }, +] as const + +interface Props { + values: BEpusdtSettingsValues + tokenConfigured: boolean + onValueChange: ( + key: K, + value: BEpusdtSettingsValues[K] + ) => void +} + +function normalizeSafeHttpUrl(raw: string): string { + const trimmed = raw.trim() + if (!trimmed) return '' + try { + const parsed = new URL(trimmed) + if (parsed.protocol === 'http:' || parsed.protocol === 'https:') { + return parsed.toString() + } + } catch { + // ignore invalid URL + } + return '' +} + +function BEpusdtNumericInput({ + id, + value, + onValueChange, + integer = false, + min = 0, +}: { + id: string + value: number + onValueChange: (next: number) => void + integer?: boolean + min?: number +}) { + const [draft, setDraft] = React.useState(() => + Number.isFinite(value) ? String(value) : '' + ) + const focusedRef = React.useRef(false) + + React.useEffect(() => { + if (!focusedRef.current) { + setDraft(Number.isFinite(value) ? String(value) : '') + } + }, [value]) + + return ( + { + focusedRef.current = true + }} + onChange={(e) => { + const raw = e.target.value + const pattern = integer ? /^\d*$/ : /^\d*\.?\d*$/ + if (!pattern.test(raw)) return + setDraft(raw) + if (raw === '' || raw === '.') return + const parsed = integer + ? Number.parseInt(raw, 10) + : Number.parseFloat(raw) + if (Number.isFinite(parsed) && parsed >= min) { + onValueChange(parsed) + } + }} + onBlur={() => { + focusedRef.current = false + const trimmed = draft.trim() + const parsed = integer + ? Number.parseInt(trimmed, 10) + : Number.parseFloat(trimmed) + if (!trimmed || !Number.isFinite(parsed) || parsed < min) { + const fallback = Math.max(min, Number.isFinite(value) ? value : min) + setDraft(String(fallback)) + onValueChange(fallback) + } else { + setDraft(String(parsed)) + onValueChange(parsed) + } + }} + /> + ) +} + +export function BEpusdtSettingsSection({ + values, + tokenConfigured, + onValueChange, +}: Props) { + const { t } = useTranslation() + const isTransactionMode = values.BEpusdtMode === 'transaction' + const currentOrigin = + typeof window !== 'undefined' ? window.location.origin : '' + const defaultWebhookUrl = currentOrigin + ? `${currentOrigin}/api/bepusdt/webhook` + : '/api/bepusdt/webhook' + + const resolvedAdminUrl = + normalizeSafeHttpUrl(values.BEpusdtAdminUrl) || + normalizeSafeHttpUrl(values.BEpusdtApiUrl) + + const handleCopyAdminUrl = async () => { + if (!resolvedAdminUrl) return + try { + await navigator.clipboard.writeText(resolvedAdminUrl) + toast.success(t('Copied to clipboard')) + } catch { + toast.error(t('Failed to copy')) + } + } + + return ( +
+
+
+

+ {t('Cryptocurrency Payment Gateway (BEpusdt)')} +

+

+ {t( + 'Accept USDT, USDC, TRX and other crypto payments via BEpusdt without affecting Epay settings.' + )} +

+
+ + {tokenConfigured + ? t('API Token Configured') + : t('API Token Not Configured')} + +
+ +
+
+
+ {t('BEpusdt Admin Console')} +
+ {resolvedAdminUrl ? ( + + {resolvedAdminUrl} + + ) : ( +

+ {t('Configure the BEpusdt Admin Login URL below to quickly open the console.')} +

+ )} +
+ {resolvedAdminUrl && ( +
+ + +
+ )} +
+ + + +

+ {t( + 'Obtain the API URL and API Token from BEpusdt Admin -> System -> Basic Settings -> API Settings.' + )} +

+

+ {t('Default webhook callback URL:')}{' '} + + {defaultWebhookUrl} + +

+
+
+ + onValueChange('BEpusdtEnabled', v)} + label={t('Enable Cryptocurrency Payment (BEpusdt)')} + description={t( + 'Display the cryptocurrency payment method on the wallet top-up page.' + )} + className='py-0' + /> + +
+
+ + onValueChange('BEpusdtApiUrl', e.target.value)} + placeholder='https://pay.btbyte.cc' + /> +

+ {t('Base URL of your BEpusdt instance without trailing slash.')} +

+
+ +
+ + onValueChange('BEpusdtAdminUrl', e.target.value)} + placeholder='https://pay.btbyte.cc/security-path' + /> +

+ {t( + 'Full BEpusdt admin login URL including the security entry path for quick access.' + )} +

+
+
+ +
+
+ + onValueChange('BEpusdtApiToken', e.target.value)} + placeholder={ + tokenConfigured + ? t('Configured — leave blank to keep unchanged') + : t('Enter BEpusdt API Token') + } + /> +

+ {t('Used to sign requests and verify payment callbacks.')} +

+
+ +
+ + + onValueChange('BEpusdtDisplayName', e.target.value) + } + placeholder={t('Cryptocurrency (USDT)')} + /> +

+ {t('Payment method label shown to users on the wallet page.')} +

+
+
+ +
+
+ + +

+ {isTransactionMode + ? t('Calls /api/v1/order/create-transaction with a fixed trade type.') + : t('Calls /api/v1/order/create-order so users can select USDT/USDC/TRX and network on the checkout page.')} +

+
+ + {!isTransactionMode ? ( +
+ + + onValueChange('BEpusdtCurrencies', e.target.value) + } + placeholder='USDT,USDC' + /> +

+ {t( + 'Comma-separated currencies (e.g. USDT,USDC or -ETH,-BNB). Leave blank to allow all enabled currencies in BEpusdt.' + )} +

+
+ ) : ( +
+ + +

+ {t('Must match an enabled wallet network in BEpusdt.')} +

+
+ )} +
+ + {isTransactionMode && ( +
+ + onValueChange('BEpusdtRate', e.target.value)} + placeholder='7.4 / ~1.02 / +0.3' + /> +

+ {t('Leave blank to use BEpusdt configured exchange rate.')} +

+
+ )} + +
+
+ + +
+ +
+ + onValueChange('BEpusdtUnitPrice', next)} + /> +

+ {t('Set 7 for CNY or 1 for USD per 1 USD balance.')} +

+
+ +
+ + onValueChange('BEpusdtMinTopUp', next)} + /> +
+ +
+ + onValueChange('BEpusdtTimeout', next)} + /> +

+ {t('Default 600s (0 uses BEpusdt default).')} +

+
+
+ +
+
+ + onValueChange('BEpusdtNotifyUrl', e.target.value)} + placeholder={defaultWebhookUrl} + /> +

+ {t('Leave blank to automatically use ServerAddress / CustomCallbackAddress + /api/bepusdt/webhook.')} +

+
+ +
+ + onValueChange('BEpusdtReturnUrl', e.target.value)} + placeholder={ + currentOrigin + ? `${currentOrigin}/wallet?show_history=true` + : 'https://example.com/wallet?show_history=true' + } + /> +

+ {t('Leave blank to return users to the wallet order history page.')} +

+
+
+
+ ) +} diff --git a/web/src/features/system-settings/integrations/payment-method-dialog.tsx b/web/src/features/system-settings/integrations/payment-method-dialog.tsx index c300ee2..9a0fbd0 100644 --- a/web/src/features/system-settings/integrations/payment-method-dialog.tsx +++ b/web/src/features/system-settings/integrations/payment-method-dialog.tsx @@ -68,6 +68,7 @@ type PaymentMethodDialogProps = { const PAYMENT_TYPE_ICON_NAMES: Record = { alipay: 'SiAlipay', + bepusdt: 'SiBitcoin', stripe: 'SiStripe', waffo_pancake: 'LuCreditCard', wxpay: 'SiWechat', @@ -109,6 +110,12 @@ export function PaymentMethodDialog({ name: 'Waffo Pancake', value: 'waffo_pancake', }, + { + iconName: 'SiBitcoin', + label: `${t('Cryptocurrency')} (bepusdt)`, + name: 'Crypto', + value: 'bepusdt', + }, ] const getPaymentTypeOption = (value: string) => paymentTypeOptions.find((option) => option.value === value) diff --git a/web/src/features/system-settings/integrations/payment-methods-visual-editor.tsx b/web/src/features/system-settings/integrations/payment-methods-visual-editor.tsx index 39d6046..4bb1d4c 100644 --- a/web/src/features/system-settings/integrations/payment-methods-visual-editor.tsx +++ b/web/src/features/system-settings/integrations/payment-methods-visual-editor.tsx @@ -45,6 +45,7 @@ type PaymentMethodsVisualEditorProps = { const PAYMENT_TYPE_ICON_NAMES: Record = { alipay: 'SiAlipay', + bepusdt: 'SiBitcoin', stripe: 'SiStripe', waffo_pancake: 'LuCreditCard', wxpay: 'SiWechat', @@ -97,6 +98,15 @@ export function PaymentMethodsVisualEditor({ type: 'waffo_pancake', }, }, + { + name: t('Cryptocurrency'), + template: { + icon: getDefaultIconName('bepusdt'), + min_topup: '10', + name: 'Crypto', + type: 'bepusdt', + }, + }, { name: t('Custom Epay method'), template: { diff --git a/web/src/features/system-settings/integrations/payment-settings-section.tsx b/web/src/features/system-settings/integrations/payment-settings-section.tsx index 892b991..dea5ac1 100644 --- a/web/src/features/system-settings/integrations/payment-settings-section.tsx +++ b/web/src/features/system-settings/integrations/payment-settings-section.tsx @@ -85,6 +85,10 @@ import { type WaffoPancakeBinding, type WaffoPancakeSettingsValues, } from './waffo-pancake-settings-section' +import { + BEpusdtSettingsSection, + type BEpusdtSettingsValues, +} from './bepusdt-settings-section' import { type PayMethod, WaffoSettingsSection, @@ -190,13 +194,46 @@ const paymentSchema = z.object({ WaffoPancakeMerchantID: z.string(), WaffoPancakePrivateKey: z.string(), WaffoPancakeReturnURL: z.string(), + BEpusdtEnabled: z.boolean(), + BEpusdtApiUrl: z.string().refine((value) => { + const trimmed = value.trim() + if (!trimmed) return true + return /^https?:\/\//.test(trimmed) + }, 'Provide a valid URL starting with http:// or https://'), + BEpusdtAdminUrl: z.string().refine((value) => { + const trimmed = value.trim() + if (!trimmed) return true + return /^https?:\/\//.test(trimmed) + }, 'Provide a valid URL starting with http:// or https://'), + BEpusdtApiToken: z.string(), + BEpusdtMode: z.string(), + BEpusdtTradeType: z.string(), + BEpusdtCurrencies: z.string(), + BEpusdtFiat: z.string(), + BEpusdtUnitPrice: z.coerce.number().min(0), + BEpusdtMinTopUp: z.coerce.number().min(1), + BEpusdtTimeout: z.coerce.number().min(0), + BEpusdtDisplayName: z.string(), + BEpusdtNotifyUrl: z.string().refine((value) => { + const trimmed = value.trim() + if (!trimmed) return true + return /^https?:\/\//.test(trimmed) + }, 'Provide a valid URL starting with http:// or https://'), + BEpusdtReturnUrl: z.string().refine((value) => { + const trimmed = value.trim() + if (!trimmed) return true + return /^https?:\/\//.test(trimmed) + }, 'Provide a valid URL starting with http:// or https://'), + BEpusdtRate: z.string(), }) type PaymentFormValues = z.infer type WaffoFormFieldValues = Omit type PaymentBaseFormValues = Omit< PaymentFormValues, - keyof WaffoFormFieldValues | keyof WaffoPancakeSettingsValues + | keyof WaffoFormFieldValues + | keyof WaffoPancakeSettingsValues + | keyof BEpusdtSettingsValues > const CURRENT_COMPLIANCE_TERMS_VERSION = 'v1' @@ -215,9 +252,29 @@ type PaymentSettingsSectionProps = { waffoPancakeDefaultValues: WaffoPancakeSettingsValues waffoPancakeProvisionedStoreID?: string waffoPancakeProvisionedProductID?: string + bepusdtDefaultValues?: BEpusdtSettingsValues + bepusdtApiTokenConfigured?: boolean complianceDefaults: PaymentComplianceDefaults } +const DEFAULT_BEPUSDT_SETTINGS: BEpusdtSettingsValues = { + BEpusdtEnabled: false, + BEpusdtApiUrl: '', + BEpusdtAdminUrl: '', + BEpusdtApiToken: '', + BEpusdtMode: 'cashier', + BEpusdtTradeType: 'usdt.trc20', + BEpusdtCurrencies: '', + BEpusdtFiat: 'CNY', + BEpusdtUnitPrice: 7, + BEpusdtMinTopUp: 1, + BEpusdtTimeout: 600, + BEpusdtDisplayName: '', + BEpusdtNotifyUrl: '', + BEpusdtReturnUrl: '', + BEpusdtRate: '', +} + function parseWaffoPayMethods(value: string): PayMethod[] { try { const parsed = JSON.parse(value || '[]') @@ -233,6 +290,8 @@ export function PaymentSettingsSection({ waffoPancakeDefaultValues, waffoPancakeProvisionedStoreID, waffoPancakeProvisionedProductID, + bepusdtDefaultValues = DEFAULT_BEPUSDT_SETTINGS, + bepusdtApiTokenConfigured = false, complianceDefaults, }: PaymentSettingsSectionProps) { const { t } = useTranslation() @@ -243,8 +302,14 @@ export function PaymentSettingsSection({ ...defaultValues, ...waffoDefaultValues, ...waffoPancakeDefaultValues, + ...bepusdtDefaultValues, }), - [defaultValues, waffoDefaultValues, waffoPancakeDefaultValues] + [ + defaultValues, + waffoDefaultValues, + waffoPancakeDefaultValues, + bepusdtDefaultValues, + ] ) const initialRef = React.useRef(initialFormValues) const defaultsSignature = React.useMemo( @@ -418,6 +483,19 @@ export function PaymentSettingsSection({ [setPaymentValue] ) + const setBEpusdtValue = React.useCallback( + ( + key: K, + value: BEpusdtSettingsValues[K] + ) => { + setPaymentValue( + key as keyof PaymentFormValues, + value as PaymentFormValues[keyof PaymentFormValues] + ) + }, + [setPaymentValue] + ) + React.useEffect(() => { const parsedDefaults = JSON.parse(defaultsSignature) as PaymentFormValues initialRef.current = parsedDefaults @@ -474,6 +552,21 @@ export function PaymentSettingsSection({ WaffoPancakeReturnURL: removeTrailingSlash( values.WaffoPancakeReturnURL.trim() ), + BEpusdtEnabled: values.BEpusdtEnabled, + BEpusdtApiUrl: removeTrailingSlash(values.BEpusdtApiUrl.trim()), + BEpusdtAdminUrl: values.BEpusdtAdminUrl.trim(), + BEpusdtApiToken: values.BEpusdtApiToken.trim(), + BEpusdtMode: values.BEpusdtMode.trim() || 'cashier', + BEpusdtTradeType: values.BEpusdtTradeType.trim() || 'usdt.trc20', + BEpusdtCurrencies: values.BEpusdtCurrencies.trim(), + BEpusdtFiat: values.BEpusdtFiat.trim() || 'CNY', + BEpusdtUnitPrice: values.BEpusdtUnitPrice, + BEpusdtMinTopUp: values.BEpusdtMinTopUp, + BEpusdtTimeout: values.BEpusdtTimeout, + BEpusdtDisplayName: values.BEpusdtDisplayName.trim(), + BEpusdtNotifyUrl: values.BEpusdtNotifyUrl.trim(), + BEpusdtReturnUrl: values.BEpusdtReturnUrl.trim(), + BEpusdtRate: values.BEpusdtRate.trim(), } const initial = { @@ -524,6 +617,24 @@ export function PaymentSettingsSection({ WaffoPancakeReturnURL: removeTrailingSlash( initialRef.current.WaffoPancakeReturnURL.trim() ), + BEpusdtEnabled: initialRef.current.BEpusdtEnabled, + BEpusdtApiUrl: removeTrailingSlash( + initialRef.current.BEpusdtApiUrl.trim() + ), + BEpusdtAdminUrl: initialRef.current.BEpusdtAdminUrl.trim(), + BEpusdtApiToken: initialRef.current.BEpusdtApiToken.trim(), + BEpusdtMode: initialRef.current.BEpusdtMode.trim() || 'cashier', + BEpusdtTradeType: + initialRef.current.BEpusdtTradeType.trim() || 'usdt.trc20', + BEpusdtCurrencies: initialRef.current.BEpusdtCurrencies.trim(), + BEpusdtFiat: initialRef.current.BEpusdtFiat.trim() || 'CNY', + BEpusdtUnitPrice: initialRef.current.BEpusdtUnitPrice, + BEpusdtMinTopUp: initialRef.current.BEpusdtMinTopUp, + BEpusdtTimeout: initialRef.current.BEpusdtTimeout, + BEpusdtDisplayName: initialRef.current.BEpusdtDisplayName.trim(), + BEpusdtNotifyUrl: initialRef.current.BEpusdtNotifyUrl.trim(), + BEpusdtReturnUrl: initialRef.current.BEpusdtReturnUrl.trim(), + BEpusdtRate: initialRef.current.BEpusdtRate.trim(), } const updates: Array<{ key: string; value: string | number | boolean }> = [] @@ -746,6 +857,93 @@ export function PaymentSettingsSection({ updates.push({ key: 'WaffoPayMethods', value: sanitized.WaffoPayMethods }) } + if (sanitized.BEpusdtApiUrl !== initial.BEpusdtApiUrl) { + updates.push({ key: 'BEpusdtApiUrl', value: sanitized.BEpusdtApiUrl }) + } + + if (sanitized.BEpusdtAdminUrl !== initial.BEpusdtAdminUrl) { + updates.push({ + key: 'BEpusdtAdminUrl', + value: sanitized.BEpusdtAdminUrl, + }) + } + + if (sanitized.BEpusdtApiToken) { + updates.push({ + key: 'BEpusdtApiToken', + value: sanitized.BEpusdtApiToken, + }) + } + + if (sanitized.BEpusdtMode !== initial.BEpusdtMode) { + updates.push({ key: 'BEpusdtMode', value: sanitized.BEpusdtMode }) + } + + if (sanitized.BEpusdtTradeType !== initial.BEpusdtTradeType) { + updates.push({ + key: 'BEpusdtTradeType', + value: sanitized.BEpusdtTradeType, + }) + } + + if (sanitized.BEpusdtCurrencies !== initial.BEpusdtCurrencies) { + updates.push({ + key: 'BEpusdtCurrencies', + value: sanitized.BEpusdtCurrencies, + }) + } + + if (sanitized.BEpusdtFiat !== initial.BEpusdtFiat) { + updates.push({ key: 'BEpusdtFiat', value: sanitized.BEpusdtFiat }) + } + + if (sanitized.BEpusdtUnitPrice !== initial.BEpusdtUnitPrice) { + updates.push({ + key: 'BEpusdtUnitPrice', + value: sanitized.BEpusdtUnitPrice, + }) + } + + if (sanitized.BEpusdtMinTopUp !== initial.BEpusdtMinTopUp) { + updates.push({ + key: 'BEpusdtMinTopUp', + value: sanitized.BEpusdtMinTopUp, + }) + } + + if (sanitized.BEpusdtTimeout !== initial.BEpusdtTimeout) { + updates.push({ key: 'BEpusdtTimeout', value: sanitized.BEpusdtTimeout }) + } + + if (sanitized.BEpusdtDisplayName !== initial.BEpusdtDisplayName) { + updates.push({ + key: 'BEpusdtDisplayName', + value: sanitized.BEpusdtDisplayName, + }) + } + + if (sanitized.BEpusdtNotifyUrl !== initial.BEpusdtNotifyUrl) { + updates.push({ + key: 'BEpusdtNotifyUrl', + value: sanitized.BEpusdtNotifyUrl, + }) + } + + if (sanitized.BEpusdtReturnUrl !== initial.BEpusdtReturnUrl) { + updates.push({ + key: 'BEpusdtReturnUrl', + value: sanitized.BEpusdtReturnUrl, + }) + } + + if (sanitized.BEpusdtRate !== initial.BEpusdtRate) { + updates.push({ key: 'BEpusdtRate', value: sanitized.BEpusdtRate }) + } + + if (sanitized.BEpusdtEnabled !== initial.BEpusdtEnabled) { + updates.push({ key: 'BEpusdtEnabled', value: sanitized.BEpusdtEnabled }) + } + const hasWaffoPancakeChanges = sanitized.WaffoPancakeMerchantID !== initial.WaffoPancakeMerchantID || sanitized.WaffoPancakePrivateKey.length > 0 || @@ -843,6 +1041,23 @@ export function PaymentSettingsSection({ WaffoPancakePrivateKey: currentFormValues.WaffoPancakePrivateKey, WaffoPancakeReturnURL: currentFormValues.WaffoPancakeReturnURL, } + const bepusdtValues: BEpusdtSettingsValues = { + BEpusdtEnabled: currentFormValues.BEpusdtEnabled, + BEpusdtApiUrl: currentFormValues.BEpusdtApiUrl, + BEpusdtAdminUrl: currentFormValues.BEpusdtAdminUrl, + BEpusdtApiToken: currentFormValues.BEpusdtApiToken, + BEpusdtMode: currentFormValues.BEpusdtMode, + BEpusdtTradeType: currentFormValues.BEpusdtTradeType, + BEpusdtCurrencies: currentFormValues.BEpusdtCurrencies, + BEpusdtFiat: currentFormValues.BEpusdtFiat, + BEpusdtUnitPrice: currentFormValues.BEpusdtUnitPrice, + BEpusdtMinTopUp: currentFormValues.BEpusdtMinTopUp, + BEpusdtTimeout: currentFormValues.BEpusdtTimeout, + BEpusdtDisplayName: currentFormValues.BEpusdtDisplayName, + BEpusdtNotifyUrl: currentFormValues.BEpusdtNotifyUrl, + BEpusdtReturnUrl: currentFormValues.BEpusdtReturnUrl, + BEpusdtRate: currentFormValues.BEpusdtRate, + } return ( @@ -925,13 +1140,14 @@ export function PaymentSettingsSection({ />
- + {t('General')} Epay {t('Stripe')} Creem Waffo Pancake Waffo + {t('Cryptocurrency')}
@@ -1761,6 +1977,14 @@ export function PaymentSettingsSection({ onPayMethodsChange={setWaffoPayMethods} /> + + + +
diff --git a/web/src/features/system-settings/types.ts b/web/src/features/system-settings/types.ts index f1f0d3c..689661c 100644 --- a/web/src/features/system-settings/types.ts +++ b/web/src/features/system-settings/types.ts @@ -355,6 +355,22 @@ export type BillingSettings = { // section (saved via /api/option/waffo-pancake/save). WaffoPancakeStoreID: string WaffoPancakeProductID: string + BEpusdtEnabled: boolean + BEpusdtApiUrl: string + BEpusdtAdminUrl: string + BEpusdtApiToken: string + BEpusdtApiTokenConfigured: boolean + BEpusdtMode: string + BEpusdtTradeType: string + BEpusdtCurrencies: string + BEpusdtFiat: string + BEpusdtUnitPrice: number + BEpusdtMinTopUp: number + BEpusdtTimeout: number + BEpusdtDisplayName: string + BEpusdtNotifyUrl: string + BEpusdtReturnUrl: string + BEpusdtRate: string 'checkin_setting.enabled': boolean 'checkin_setting.min_quota': number 'checkin_setting.max_quota': number diff --git a/web/src/features/system-settings/utils/numeric-field.ts b/web/src/features/system-settings/utils/numeric-field.ts index 3fd8be1..797ce92 100644 --- a/web/src/features/system-settings/utils/numeric-field.ts +++ b/web/src/features/system-settings/utils/numeric-field.ts @@ -79,11 +79,19 @@ export function safeNumberFieldProps< >(field: ControllerRenderProps): SafeNumberFieldProps { const raw = field.value as unknown const display: number | '' = - typeof raw === 'number' && Number.isFinite(raw) ? raw : '' + raw === '' + ? '' + : typeof raw === 'number' && Number.isFinite(raw) + ? raw + : '' return { value: display, onChange: (event) => { + if (event.target.value === '') { + ;(field.onChange as (value: number | '') => void)('') + return + } const next = event.target.valueAsNumber if (Number.isFinite(next)) { ;(field.onChange as (value: number) => void)(next) diff --git a/web/src/features/wallet/api.ts b/web/src/features/wallet/api.ts index e2f7073..a76d72b 100644 --- a/web/src/features/wallet/api.ts +++ b/web/src/features/wallet/api.ts @@ -39,6 +39,8 @@ import type { WaffoPaymentResponse, WaffoPancakePaymentRequest, WaffoPancakePaymentResponse, + BEpusdtPaymentRequest, + BEpusdtPaymentResponse, } from './types' // ============================================================================ @@ -181,6 +183,30 @@ export async function requestWaffoPancakePayment( return res.data } +/** + * Calculate payment amount for BEpusdt cryptocurrency payment + */ +export async function calculateBEpusdtAmount( + request: AmountRequest +): Promise { + const res = await api.post('/api/user/bepusdt/amount', request, { + skipBusinessError: true, + } as Record) + return res.data +} + +/** + * Request BEpusdt cryptocurrency payment + */ +export async function requestBEpusdtPayment( + request: BEpusdtPaymentRequest +): Promise { + const res = await api.post('/api/user/bepusdt/pay', request, { + skipBusinessError: true, + } as Record) + return res.data +} + /** * Get affiliate code */ diff --git a/web/src/features/wallet/components/dialogs/payment-confirm-dialog.tsx b/web/src/features/wallet/components/dialogs/payment-confirm-dialog.tsx index 30fd955..0375ded 100644 --- a/web/src/features/wallet/components/dialogs/payment-confirm-dialog.tsx +++ b/web/src/features/wallet/components/dialogs/payment-confirm-dialog.tsx @@ -33,7 +33,7 @@ import { Skeleton } from '@/components/ui/skeleton' import { formatLocalCurrencyAmount } from '@/lib/currency' import { DEFAULT_DISCOUNT_RATE } from '../../constants' -import { formatCurrency, getPaymentIcon } from '../../lib' +import { formatCurrency, getPaymentIcon, isBEpusdtPayment } from '../../lib' import type { PaymentMethod } from '../../types' interface PaymentConfirmDialogProps { @@ -47,6 +47,24 @@ interface PaymentConfirmDialogProps { processing: boolean discountRate?: number usdExchangeRate?: number + currencyCode?: string +} + +function formatPaymentAmount(value: number, currencyCode?: string): string { + if (!currencyCode) { + return formatCurrency(value) + } + const code = currencyCode.toUpperCase() + const symbols: Record = { + CNY: '¥', + USD: '$', + EUR: '€', + GBP: '£', + JPY: '¥', + } + const symbol = symbols[code] + const formatted = value.toFixed(2) + return symbol ? `${symbol}${formatted} (${code})` : `${formatted} ${code}` } export function PaymentConfirmDialog({ @@ -60,9 +78,12 @@ export function PaymentConfirmDialog({ processing, discountRate = DEFAULT_DISCOUNT_RATE, usdExchangeRate = 1, + currencyCode, }: PaymentConfirmDialogProps) { const { t } = useTranslation() - const hasDiscount = discountRate > 0 && discountRate < 1 && paymentAmount > 0 + const hidePayAmount = isBEpusdtPayment(paymentMethod?.type) + const hasDiscount = + !hidePayAmount && discountRate > 0 && discountRate < 1 && paymentAmount > 0 const originalAmount = hasDiscount ? paymentAmount / discountRate : 0 const discountAmount = hasDiscount ? originalAmount - paymentAmount : 0 @@ -92,32 +113,34 @@ export function PaymentConfirmDialog({ -
- - {t('You Pay')} - - {calculating ? ( - - ) : ( -
- - {formatCurrency(paymentAmount)} - - {hasDiscount && ( - - {formatCurrency(originalAmount)} + {!hidePayAmount && ( +
+ + {t('You Pay')} + + {calculating ? ( + + ) : ( +
+ + {formatPaymentAmount(paymentAmount, currencyCode)} - )} -
- )} -
+ {hasDiscount && ( + + {formatPaymentAmount(originalAmount, currencyCode)} + + )} +
+ )} +
+ )} - {hasDiscount && !calculating && ( + {!hidePayAmount && hasDiscount && !calculating && (
{t('You save')} - {formatCurrency(discountAmount)} + {formatPaymentAmount(discountAmount, currencyCode)}
diff --git a/web/src/features/wallet/components/recharge-form-card.tsx b/web/src/features/wallet/components/recharge-form-card.tsx index c98b638..4d49800 100644 --- a/web/src/features/wallet/components/recharge-form-card.tsx +++ b/web/src/features/wallet/components/recharge-form-card.tsx @@ -34,7 +34,7 @@ import { TooltipProvider, TooltipTrigger, } from '@/components/ui/tooltip' -import { formatNumber } from '@/lib/format' +import { formatLocalCurrencyAmount } from '@/lib/currency' import { cn } from '@/lib/utils' import { @@ -43,6 +43,7 @@ import { getPaymentIcon, getMinTopupAmount, calculatePresetPricing, + isBEpusdtPayment, } from '../lib' import type { PaymentMethod, @@ -133,6 +134,7 @@ export function RechargeFormCard({ const hasConfigurableTopup = topupInfo?.enable_online_topup || topupInfo?.enable_stripe_topup || + topupInfo?.enable_bepusdt_topup || enableWaffoTopup || enableWaffoPancakeTopup const hasAnyTopup = hasConfigurableTopup || enableCreemTopup @@ -257,7 +259,11 @@ export function RechargeFormCard({ >
- {formatNumber(displayValue)} + {formatLocalCurrencyAmount(displayValue, { + digitsLarge: 2, + digitsSmall: 2, + abbreviate: false, + })}
{hasDiscount && (
@@ -299,15 +305,33 @@ export function RechargeFormCard({ {t('Custom Amount')}
- handleAmountChange(e.target.value)} - min={minTopup} - placeholder={t('Minimum {{amount}}', { amount: minTopup })} - className='h-9 text-base sm:h-10 sm:text-lg' - /> +
+ + {formatLocalCurrencyAmount(0, { + digitsLarge: 0, + digitsSmall: 0, + abbreviate: false, + }).replace(/[\d.,\s-]/g, '') || '$'} + + handleAmountChange(e.target.value)} + min={minTopup} + placeholder={t('Minimum {{amount}}', { + amount: formatLocalCurrencyAmount( + minTopup * usdExchangeRate, + { + digitsLarge: 2, + digitsSmall: 2, + abbreviate: false, + } + ), + })} + className='h-9 pl-7 text-base sm:h-10 sm:text-lg' + /> +
{t('Amount to pay:')} @@ -330,18 +354,30 @@ export function RechargeFormCard({ {hasStandardPaymentMethods ? (
{topupInfo?.pay_methods?.map((method) => { - const minTopup = Math.max( - method.min_topup || 0, - getMinTopupAmount(topupInfo) - ) + const minTopup = isBEpusdtPayment(method.type) + ? Number(method.min_topup) || + topupInfo?.bepusdt_min_topup || + 1 + : Math.max( + method.min_topup || 0, + getMinTopupAmount(topupInfo) + ) const disabled = minTopup > topupAmount + const formattedMin = formatLocalCurrencyAmount( + minTopup * usdExchangeRate, + { + digitsLarge: 2, + digitsSmall: 2, + abbreviate: false, + } + ) const disabledReason = disabled ? t('Minimum topup amount: {{amount}}', { - amount: minTopup, + amount: formattedMin, }) : undefined const disabledLabel = disabled - ? `${t('Minimum:')} ${minTopup}` + ? `${t('Minimum:')} ${formattedMin}` : undefined const button = ( diff --git a/web/src/features/wallet/constants.ts b/web/src/features/wallet/constants.ts index 50bb45e..590f840 100644 --- a/web/src/features/wallet/constants.ts +++ b/web/src/features/wallet/constants.ts @@ -36,6 +36,7 @@ export const PAYMENT_TYPES = { CREEM: 'creem', WAFFO: 'waffo', WAFFO_PANCAKE: 'waffo_pancake', + BEPUSDT: 'bepusdt', } as const /** @@ -53,6 +54,7 @@ export const PAYMENT_ICON_COLORS = { [PAYMENT_TYPES.CREEM]: '#6366F1', [PAYMENT_TYPES.WAFFO]: '#2563EB', [PAYMENT_TYPES.WAFFO_PANCAKE]: '#F97316', + [PAYMENT_TYPES.BEPUSDT]: '#26A17B', } as const /** diff --git a/web/src/features/wallet/hooks/index.ts b/web/src/features/wallet/hooks/index.ts index e11d63c..0d4e108 100644 --- a/web/src/features/wallet/hooks/index.ts +++ b/web/src/features/wallet/hooks/index.ts @@ -27,3 +27,4 @@ export * from './use-redemption' export * from './use-creem-payment' export * from './use-waffo-payment' export * from './use-waffo-pancake-payment' +export * from './use-bepusdt-payment' diff --git a/web/src/features/wallet/hooks/use-bepusdt-payment.ts b/web/src/features/wallet/hooks/use-bepusdt-payment.ts new file mode 100644 index 0000000..6cbcb64 --- /dev/null +++ b/web/src/features/wallet/hooks/use-bepusdt-payment.ts @@ -0,0 +1,100 @@ +/* +Copyright (C) 2023-2026 QuantumNous + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +For commercial licensing, please contact support@quantumnous.com +*/ +import i18next from 'i18next' +import { useState, useCallback } from 'react' +import { toast } from 'sonner' + +import { handleServerError } from '@/lib/handle-server-error' + +import { requestBEpusdtPayment, isApiSuccess } from '../api' +import { getPaymentErrorTranslation } from '../lib' + +function getPaymentUrl(data: unknown): string | null { + if (!data || typeof data !== 'object') { + return null + } + if ('payment_url' in data && typeof data.payment_url === 'string') { + return data.payment_url + } + return null +} + +function isSafeHttpUrl(value: string): boolean { + const trimmed = value.trim() + if (!trimmed) { + return false + } + try { + const parsed = new URL(trimmed) + return parsed.protocol === 'http:' || parsed.protocol === 'https:' + } catch { + return false + } +} + +function getErrorMessage(message: string | undefined, data: unknown): string { + if (typeof data === 'string' && data.trim()) { + return data + } + return ( + (message && message !== 'success' ? message : undefined) || + i18next.t('Payment request failed') + ) +} + +export function useBEpusdtPayment() { + const [processing, setProcessing] = useState(false) + + const processBEpusdtPayment = useCallback(async (topupAmount: number) => { + setProcessing(true) + + try { + const response = await requestBEpusdtPayment({ + amount: Math.floor(topupAmount), + }) + + if (isApiSuccess(response)) { + const paymentUrl = getPaymentUrl(response.data) + if (paymentUrl) { + if (!isSafeHttpUrl(paymentUrl)) { + toast.error(i18next.t('Invalid payment redirect URL')) + return false + } + toast.success(i18next.t('Redirecting to payment page...')) + window.location.href = paymentUrl + return true + } + } + + handleServerError(response, undefined, { + title: + getPaymentErrorTranslation(response) ?? + getErrorMessage(response.message, response.data), + }) + return false + } catch (error) { + handleServerError(error, i18next.t('Payment request failed')) + return false + } finally { + setProcessing(false) + } + }, []) + + return { processing, processBEpusdtPayment } +} diff --git a/web/src/features/wallet/hooks/use-payment.ts b/web/src/features/wallet/hooks/use-payment.ts index 19ec308..816f1d5 100644 --- a/web/src/features/wallet/hooks/use-payment.ts +++ b/web/src/features/wallet/hooks/use-payment.ts @@ -27,6 +27,7 @@ import { calculateStripeAmount, calculateWaffoAmount, calculateWaffoPancakeAmount, + calculateBEpusdtAmount, requestPayment, requestStripePayment, isApiSuccess, @@ -35,6 +36,7 @@ import { isStripePayment, isWaffoPayment, isWaffoPancakePayment, + isBEpusdtPayment, submitPaymentForm, } from '../lib' import type { AmountRequest, AmountResponse } from '../types' @@ -50,6 +52,7 @@ export interface PaymentAmountCalculators { stripe: AmountCalculator waffo: AmountCalculator waffoPancake: AmountCalculator + bepusdt?: AmountCalculator } const defaultPaymentAmountCalculators: PaymentAmountCalculators = { @@ -57,6 +60,7 @@ const defaultPaymentAmountCalculators: PaymentAmountCalculators = { stripe: calculateStripeAmount, waffo: calculateWaffoAmount, waffoPancake: calculateWaffoPancakeAmount, + bepusdt: calculateBEpusdtAmount, } export async function requestPaymentAmount( @@ -71,6 +75,8 @@ export async function requestPaymentAmount( calculator = calculators.waffo } else if (isWaffoPancakePayment(paymentType)) { calculator = calculators.waffoPancake + } else if (isBEpusdtPayment(paymentType) && calculators.bepusdt) { + calculator = calculators.bepusdt } const response = await calculator({ amount: topupAmount }) diff --git a/web/src/features/wallet/index.tsx b/web/src/features/wallet/index.tsx index 5a9cb9e..5faf46e 100644 --- a/web/src/features/wallet/index.tsx +++ b/web/src/features/wallet/index.tsx @@ -41,11 +41,13 @@ import { useCreemPayment, useWaffoPayment, useWaffoPancakePayment, + useBEpusdtPayment, } from './hooks' import { getDefaultPaymentType, getMinTopupAmount, dispatchSelectedPayment, + isBEpusdtPayment, } from './lib' import type { UserWalletData, @@ -108,6 +110,8 @@ export function Wallet(props: WalletProps) { const { processing: waffoProcessing, processWaffoPayment } = useWaffoPayment() const { processing: pancakeProcessing, processWaffoPancakePayment } = useWaffoPancakePayment() + const { processing: bepusdtProcessing, processBEpusdtPayment } = + useBEpusdtPayment() // Fetch and refresh user data const fetchUser = useCallback(async () => { @@ -177,13 +181,17 @@ export function Wallet(props: WalletProps) { try { // Validate minimum topup - const minTopup = getMinTopupAmount(topupInfo) + const minTopup = isBEpusdtPayment(method.type) + ? Number(method.min_topup) || topupInfo?.bepusdt_min_topup || 1 + : getMinTopupAmount(topupInfo) if (topupAmount < minTopup) { return } // Calculate payment amount and show confirmation dialog - await calculatePaymentAmount(topupAmount, method.type) + if (!isBEpusdtPayment(method.type)) { + await calculatePaymentAmount(topupAmount, method.type) + } setConfirmDialogOpen(true) } finally { setPaymentLoading(null) @@ -202,6 +210,7 @@ export function Wallet(props: WalletProps) { regular: processPayment, waffo: processWaffoPayment, waffoPancake: processWaffoPancakePayment, + bepusdt: processBEpusdtPayment, } ) @@ -360,9 +369,19 @@ export function Wallet(props: WalletProps) { paymentAmount={paymentAmount} paymentMethod={selectedPaymentMethod} calculating={calculating} - processing={processing || waffoProcessing || pancakeProcessing} + processing={ + processing || + waffoProcessing || + pancakeProcessing || + bepusdtProcessing + } discountRate={getDiscountRate()} usdExchangeRate={effectiveUsdExchangeRate} + currencyCode={ + selectedPaymentMethod && isBEpusdtPayment(selectedPaymentMethod.type) + ? topupInfo?.bepusdt_fiat + : undefined + } /> = 1 ? 2 : 4, }).format(numeric) + return `¥${formatted}` } /** diff --git a/web/src/features/wallet/lib/payment.ts b/web/src/features/wallet/lib/payment.ts index 2ea8fa2..a9bb53f 100644 --- a/web/src/features/wallet/lib/payment.ts +++ b/web/src/features/wallet/lib/payment.ts @@ -111,10 +111,25 @@ export function isWaffoPancakePayment(paymentType: string): boolean { return paymentType === PAYMENT_TYPES.WAFFO_PANCAKE } +/** + * Check if payment method is BEpusdt cryptocurrency + */ +export function isBEpusdtPayment(paymentType: string | undefined): boolean { + if (!paymentType) return false + const normalized = paymentType.trim().toLowerCase() + return ( + normalized === PAYMENT_TYPES.BEPUSDT || + normalized === 'crypto' || + normalized === '数字货币' || + normalized === '數字貨幣' + ) +} + export interface PaymentProcessors { regular: (topupAmount: number, paymentType: string) => Promise waffo: (topupAmount: number, payMethodIndex: number) => Promise waffoPancake: (topupAmount: number) => Promise + bepusdt?: (topupAmount: number) => Promise } export async function dispatchSelectedPayment( @@ -134,6 +149,10 @@ export async function dispatchSelectedPayment( return processors.waffoPancake(topupAmount) } + if (isBEpusdtPayment(paymentMethod.type) && processors.bepusdt) { + return processors.bepusdt(topupAmount) + } + return processors.regular(topupAmount, paymentMethod.type) } @@ -162,6 +181,10 @@ export function getDefaultPaymentType(topupInfo: TopupInfo | null): string { return PAYMENT_TYPES.WAFFO_PANCAKE } + if (topupInfo.enable_bepusdt_topup) { + return PAYMENT_TYPES.BEPUSDT + } + return DEFAULT_PAYMENT_TYPE } @@ -189,6 +212,10 @@ export function getMinTopupAmount(topupInfo: TopupInfo | null): number { return topupInfo.waffo_pancake_min_topup || DEFAULT_MIN_TOPUP } + if (topupInfo.enable_bepusdt_topup) { + return topupInfo.bepusdt_min_topup || DEFAULT_MIN_TOPUP + } + return DEFAULT_MIN_TOPUP } diff --git a/web/src/features/wallet/lib/ui.tsx b/web/src/features/wallet/lib/ui.tsx index 567053b..e18dfed 100644 --- a/web/src/features/wallet/lib/ui.tsx +++ b/web/src/features/wallet/lib/ui.tsx @@ -17,7 +17,7 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ import i18next from 'i18next' -import { CreditCard, Landmark } from 'lucide-react' +import { Coins, CreditCard, Landmark } from 'lucide-react' import type { ReactNode } from 'react' import { IconAlipay, IconWeChat, IconStripe } from '@/assets/brand-icons' @@ -154,6 +154,13 @@ export function getPaymentIcon( /> ) + case PAYMENT_TYPES.BEPUSDT: + return ( + + ) default: return } diff --git a/web/src/features/wallet/types.ts b/web/src/features/wallet/types.ts index 5da08f0..4ef768e 100644 --- a/web/src/features/wallet/types.ts +++ b/web/src/features/wallet/types.ts @@ -45,6 +45,14 @@ export type CreemPaymentResponse = ApiResponse<{ checkout_url: string }> export type WaffoPaymentResponse = ApiResponse< { payment_url?: string } | string > +export type BEpusdtPaymentResponse = ApiResponse< + | { + payment_url?: string + trade_id?: string + trade_no?: string + } + | string +> export type WaffoPancakePaymentResponse = ApiResponse< | { checkout_url?: string @@ -150,6 +158,12 @@ export interface TopupInfo { enable_waffo_pancake_topup?: boolean /** Minimum topup amount for Waffo Pancake */ waffo_pancake_min_topup?: number + /** Whether BEpusdt cryptocurrency topup is enabled */ + enable_bepusdt_topup?: boolean + /** Minimum topup amount for BEpusdt */ + bepusdt_min_topup?: number + /** Fiat currency code used by BEpusdt */ + bepusdt_fiat?: string /** Whether redemption code usage is enabled */ enable_redemption?: boolean /** Whether compliance confirmation has been completed */ @@ -204,6 +218,14 @@ export interface WaffoPancakePaymentRequest { amount: number } +/** + * BEpusdt cryptocurrency payment request parameters + */ +export interface BEpusdtPaymentRequest { + /** Topup amount */ + amount: number +} + /** * Amount calculation request */ diff --git a/web/src/i18n/locales/en.json b/web/src/i18n/locales/en.json index a2a9e9e..0aa1f2f 100644 --- a/web/src/i18n/locales/en.json +++ b/web/src/i18n/locales/en.json @@ -2965,7 +2965,7 @@ "footer.columns.related.links.oneApi": "One API", "footer.columns.related.title": "Related Projects", "footer.defaultCopyright": "All rights reserved.", - "footer.new\u0061pi.projectAttributionSuffix": "All rights reserved. Designed and developed by the project contributors.", + "footer.newapi.projectAttributionSuffix": "All rights reserved. Designed and developed by the project contributors.", "For a stronger password": "For a stronger password", "For advanced custom channels this applies only to /v1/responses routes without protocol conversion.": "For advanced custom channels this applies only to /v1/responses routes without protocol conversion.", "For channels added after May 10, 2025, no need to remove \".\" from model names during deployment": "For channels added after May 10, 2025, no need to remove \".\" from model names during deployment", @@ -7757,6 +7757,52 @@ "Zhipu V4": "Zhipu V4", "Zoom": "Zoom", "By clicking sign in, you agree to our": "By clicking sign in, you agree to our", - "By creating an account, you agree to our": "By creating an account, you agree to our" + "By creating an account, you agree to our": "By creating an account, you agree to our", + "Cryptocurrency": "Cryptocurrency", + "Cryptocurrency (USDT)": "Cryptocurrency (USDT)", + "Cryptocurrency Payment Gateway (BEpusdt)": "Cryptocurrency Payment Gateway (BEpusdt)", + "Accept USDT, USDC, TRX and other crypto payments via BEpusdt without affecting Epay settings.": "Accept USDT, USDC, TRX and other crypto payments via BEpusdt without affecting Epay settings.", + "API Token Configured": "API Token Configured", + "API Token Not Configured": "API Token Not Configured", + "Obtain the API URL and API Token from BEpusdt Admin -> System -> Basic Settings -> API Settings.": "Obtain the API URL and API Token from BEpusdt Admin -> System -> Basic Settings -> API Settings.", + "Default webhook callback URL:": "Default webhook callback URL:", + "Enable Cryptocurrency Payment (BEpusdt)": "Enable Cryptocurrency Payment (BEpusdt)", + "Display the cryptocurrency payment method on the wallet top-up page.": "Display the cryptocurrency payment method on the wallet top-up page.", + "BEpusdt API URL": "BEpusdt API URL", + "Base URL of your BEpusdt instance without trailing slash.": "Base URL of your BEpusdt instance without trailing slash.", + "BEpusdt API Token": "BEpusdt API Token", + "Configured — leave blank to keep unchanged": "Configured — leave blank to keep unchanged", + "Enter BEpusdt API Token": "Enter BEpusdt API Token", + "Used to sign requests and verify payment callbacks.": "Used to sign requests and verify payment callbacks.", + "Checkout Mode": "Checkout Mode", + "Cashier Mode (User chooses coin & network)": "Cashier Mode (User chooses coin & network)", + "Fixed Trade Type (create-transaction)": "Fixed Trade Type (create-transaction)", + "Calls /api/v1/order/create-transaction with a fixed trade type.": "Calls /api/v1/order/create-transaction with a fixed trade type.", + "Calls /api/v1/order/create-order so users can select USDT/USDC/TRX and network on the checkout page.": "Calls /api/v1/order/create-order so users can select USDT/USDC/TRX and network on the checkout page.", + "Payment method label shown to users on the wallet page.": "Payment method label shown to users on the wallet page.", + "Trade Type": "Trade Type", + "Must match an enabled wallet network in BEpusdt.": "Must match an enabled wallet network in BEpusdt.", + "Forced Exchange Rate (Optional)": "Forced Exchange Rate (Optional)", + "Leave blank to use BEpusdt configured exchange rate.": "Leave blank to use BEpusdt configured exchange rate.", + "Allowed Currencies (Optional)": "Allowed Currencies (Optional)", + "Comma-separated currencies (e.g. USDT,USDC or -ETH,-BNB). Leave blank to allow all enabled currencies in BEpusdt.": "Comma-separated currencies (e.g. USDT,USDC or -ETH,-BNB). Leave blank to allow all enabled currencies in BEpusdt.", + "Fiat Currency": "Fiat Currency", + "Unit Price (Fiat / USD)": "Unit Price (Fiat / USD)", + "Set 7 for CNY or 1 for USD per 1 USD balance.": "Set 7 for CNY or 1 for USD per 1 USD balance.", + "Minimum Top-up (USD)": "Minimum Top-up (USD)", + "Order Timeout (Seconds)": "Order Timeout (Seconds)", + "Default 600s (0 uses BEpusdt default).": "Default 600s (0 uses BEpusdt default).", + "Custom Webhook URL (Optional)": "Custom Webhook URL (Optional)", + "Leave blank to automatically use ServerAddress / CustomCallbackAddress + /api/bepusdt/webhook.": "Leave blank to automatically use ServerAddress / CustomCallbackAddress + /api/bepusdt/webhook.", + "Custom Return URL (Optional)": "Custom Return URL (Optional)", + "Leave blank to return users to the wallet order history page.": "Leave blank to return users to the wallet order history page.", + "Cryptocurrency payment is not enabled": "Cryptocurrency payment is not enabled", + "Failed to create payment order": "Failed to create payment order", + "Server address is not configured": "Server address is not configured", + "BEpusdt Admin Console": "BEpusdt Admin Console", + "Configure the BEpusdt Admin Login URL below to quickly open the console.": "Configure the BEpusdt Admin Login URL below to quickly open the console.", + "Open BEpusdt Admin": "Open BEpusdt Admin", + "BEpusdt Admin Login URL": "BEpusdt Admin Login URL", + "Full BEpusdt admin login URL including the security entry path for quick access.": "Full BEpusdt admin login URL including the security entry path for quick access." } } diff --git a/web/src/i18n/locales/fr.json b/web/src/i18n/locales/fr.json index 5778aae..cbfc413 100644 --- a/web/src/i18n/locales/fr.json +++ b/web/src/i18n/locales/fr.json @@ -2965,7 +2965,7 @@ "footer.columns.related.links.oneApi": "One API", "footer.columns.related.title": "Projets liés", "footer.defaultCopyright": "Tous droits réservés.", - "footer.new\u0061pi.projectAttributionSuffix": "Tous droits réservés. Conçu et développé par les contributeurs du projet.", + "footer.newapi.projectAttributionSuffix": "Tous droits réservés. Conçu et développé par les contributeurs du projet.", "For a stronger password": "Pour un mot de passe plus robuste", "For advanced custom channels this applies only to /v1/responses routes without protocol conversion.": "Pour les canaux personnalisés avancés, ceci ne s’applique qu’aux routes /v1/responses sans conversion de protocole.", "For channels added after May 10, 2025, no need to remove \".\" from model names during deployment": "Pour les canaux ajoutés après le 10 mai 2025, pas besoin de supprimer \".\" des noms de modèles lors du déploiement", @@ -7757,6 +7757,52 @@ "Zhipu V4": "Zhipu V4", "Zoom": "Zoom", "By clicking sign in, you agree to our": "En cliquant sur se connecter, vous acceptez nos", - "By creating an account, you agree to our": "En créant un compte, vous acceptez nos" + "By creating an account, you agree to our": "En créant un compte, vous acceptez nos", + "Cryptocurrency": "Cryptocurrency", + "Cryptocurrency (USDT)": "Cryptocurrency (USDT)", + "Cryptocurrency Payment Gateway (BEpusdt)": "Cryptocurrency Payment Gateway (BEpusdt)", + "Accept USDT, USDC, TRX and other crypto payments via BEpusdt without affecting Epay settings.": "Accept USDT, USDC, TRX and other crypto payments via BEpusdt without affecting Epay settings.", + "API Token Configured": "API Token Configured", + "API Token Not Configured": "API Token Not Configured", + "Obtain the API URL and API Token from BEpusdt Admin -> System -> Basic Settings -> API Settings.": "Obtain the API URL and API Token from BEpusdt Admin -> System -> Basic Settings -> API Settings.", + "Default webhook callback URL:": "Default webhook callback URL:", + "Enable Cryptocurrency Payment (BEpusdt)": "Enable Cryptocurrency Payment (BEpusdt)", + "Display the cryptocurrency payment method on the wallet top-up page.": "Display the cryptocurrency payment method on the wallet top-up page.", + "BEpusdt API URL": "BEpusdt API URL", + "Base URL of your BEpusdt instance without trailing slash.": "Base URL of your BEpusdt instance without trailing slash.", + "BEpusdt API Token": "BEpusdt API Token", + "Configured — leave blank to keep unchanged": "Configured — leave blank to keep unchanged", + "Enter BEpusdt API Token": "Enter BEpusdt API Token", + "Used to sign requests and verify payment callbacks.": "Used to sign requests and verify payment callbacks.", + "Checkout Mode": "Checkout Mode", + "Cashier Mode (User chooses coin & network)": "Cashier Mode (User chooses coin & network)", + "Fixed Trade Type (create-transaction)": "Fixed Trade Type (create-transaction)", + "Calls /api/v1/order/create-transaction with a fixed trade type.": "Calls /api/v1/order/create-transaction with a fixed trade type.", + "Calls /api/v1/order/create-order so users can select USDT/USDC/TRX and network on the checkout page.": "Calls /api/v1/order/create-order so users can select USDT/USDC/TRX and network on the checkout page.", + "Payment method label shown to users on the wallet page.": "Payment method label shown to users on the wallet page.", + "Trade Type": "Trade Type", + "Must match an enabled wallet network in BEpusdt.": "Must match an enabled wallet network in BEpusdt.", + "Forced Exchange Rate (Optional)": "Forced Exchange Rate (Optional)", + "Leave blank to use BEpusdt configured exchange rate.": "Leave blank to use BEpusdt configured exchange rate.", + "Allowed Currencies (Optional)": "Allowed Currencies (Optional)", + "Comma-separated currencies (e.g. USDT,USDC or -ETH,-BNB). Leave blank to allow all enabled currencies in BEpusdt.": "Comma-separated currencies (e.g. USDT,USDC or -ETH,-BNB). Leave blank to allow all enabled currencies in BEpusdt.", + "Fiat Currency": "Fiat Currency", + "Unit Price (Fiat / USD)": "Unit Price (Fiat / USD)", + "Set 7 for CNY or 1 for USD per 1 USD balance.": "Set 7 for CNY or 1 for USD per 1 USD balance.", + "Minimum Top-up (USD)": "Minimum Top-up (USD)", + "Order Timeout (Seconds)": "Order Timeout (Seconds)", + "Default 600s (0 uses BEpusdt default).": "Default 600s (0 uses BEpusdt default).", + "Custom Webhook URL (Optional)": "Custom Webhook URL (Optional)", + "Leave blank to automatically use ServerAddress / CustomCallbackAddress + /api/bepusdt/webhook.": "Leave blank to automatically use ServerAddress / CustomCallbackAddress + /api/bepusdt/webhook.", + "Custom Return URL (Optional)": "Custom Return URL (Optional)", + "Leave blank to return users to the wallet order history page.": "Leave blank to return users to the wallet order history page.", + "Cryptocurrency payment is not enabled": "Cryptocurrency payment is not enabled", + "Failed to create payment order": "Failed to create payment order", + "Server address is not configured": "Server address is not configured", + "BEpusdt Admin Console": "BEpusdt Admin Console", + "Configure the BEpusdt Admin Login URL below to quickly open the console.": "Configure the BEpusdt Admin Login URL below to quickly open the console.", + "Open BEpusdt Admin": "Open BEpusdt Admin", + "BEpusdt Admin Login URL": "BEpusdt Admin Login URL", + "Full BEpusdt admin login URL including the security entry path for quick access.": "Full BEpusdt admin login URL including the security entry path for quick access." } } diff --git a/web/src/i18n/locales/ja.json b/web/src/i18n/locales/ja.json index 4ad9f39..c3507aa 100644 --- a/web/src/i18n/locales/ja.json +++ b/web/src/i18n/locales/ja.json @@ -2965,7 +2965,7 @@ "footer.columns.related.links.oneApi": "1つのAPI", "footer.columns.related.title": "関連プロジェクト", "footer.defaultCopyright": "すべての権利を留保します。", - "footer.new\u0061pi.projectAttributionSuffix": "すべての権利を留保します。プロジェクトコントリビューターにより設計・開発されています。", + "footer.newapi.projectAttributionSuffix": "すべての権利を留保します。プロジェクトコントリビューターにより設計・開発されています。", "For a stronger password": "より強いパスワードにするには", "For advanced custom channels this applies only to /v1/responses routes without protocol conversion.": "高度なカスタムチャネルでは、プロトコル変換を行わない /v1/responses ルートにのみ適用されます。", "For channels added after May 10, 2025, no need to remove \".\" from model names during deployment": "2025 年 5 月 10 日以降に追加されたチャネルの場合、デプロイ時にモデル名から「.」を削除する必要はありません", @@ -7757,6 +7757,52 @@ "Zhipu V4": "Zhipu V 4", "Zoom": "ズーム", "By clicking sign in, you agree to our": "サインインをクリックすると、以下に同意したことになります:", - "By creating an account, you agree to our": "アカウントを作成すると、以下に同意したことになります:" + "By creating an account, you agree to our": "アカウントを作成すると、以下に同意したことになります:", + "Cryptocurrency": "Cryptocurrency", + "Cryptocurrency (USDT)": "Cryptocurrency (USDT)", + "Cryptocurrency Payment Gateway (BEpusdt)": "Cryptocurrency Payment Gateway (BEpusdt)", + "Accept USDT, USDC, TRX and other crypto payments via BEpusdt without affecting Epay settings.": "Accept USDT, USDC, TRX and other crypto payments via BEpusdt without affecting Epay settings.", + "API Token Configured": "API Token Configured", + "API Token Not Configured": "API Token Not Configured", + "Obtain the API URL and API Token from BEpusdt Admin -> System -> Basic Settings -> API Settings.": "Obtain the API URL and API Token from BEpusdt Admin -> System -> Basic Settings -> API Settings.", + "Default webhook callback URL:": "Default webhook callback URL:", + "Enable Cryptocurrency Payment (BEpusdt)": "Enable Cryptocurrency Payment (BEpusdt)", + "Display the cryptocurrency payment method on the wallet top-up page.": "Display the cryptocurrency payment method on the wallet top-up page.", + "BEpusdt API URL": "BEpusdt API URL", + "Base URL of your BEpusdt instance without trailing slash.": "Base URL of your BEpusdt instance without trailing slash.", + "BEpusdt API Token": "BEpusdt API Token", + "Configured — leave blank to keep unchanged": "Configured — leave blank to keep unchanged", + "Enter BEpusdt API Token": "Enter BEpusdt API Token", + "Used to sign requests and verify payment callbacks.": "Used to sign requests and verify payment callbacks.", + "Checkout Mode": "Checkout Mode", + "Cashier Mode (User chooses coin & network)": "Cashier Mode (User chooses coin & network)", + "Fixed Trade Type (create-transaction)": "Fixed Trade Type (create-transaction)", + "Calls /api/v1/order/create-transaction with a fixed trade type.": "Calls /api/v1/order/create-transaction with a fixed trade type.", + "Calls /api/v1/order/create-order so users can select USDT/USDC/TRX and network on the checkout page.": "Calls /api/v1/order/create-order so users can select USDT/USDC/TRX and network on the checkout page.", + "Payment method label shown to users on the wallet page.": "Payment method label shown to users on the wallet page.", + "Trade Type": "Trade Type", + "Must match an enabled wallet network in BEpusdt.": "Must match an enabled wallet network in BEpusdt.", + "Forced Exchange Rate (Optional)": "Forced Exchange Rate (Optional)", + "Leave blank to use BEpusdt configured exchange rate.": "Leave blank to use BEpusdt configured exchange rate.", + "Allowed Currencies (Optional)": "Allowed Currencies (Optional)", + "Comma-separated currencies (e.g. USDT,USDC or -ETH,-BNB). Leave blank to allow all enabled currencies in BEpusdt.": "Comma-separated currencies (e.g. USDT,USDC or -ETH,-BNB). Leave blank to allow all enabled currencies in BEpusdt.", + "Fiat Currency": "Fiat Currency", + "Unit Price (Fiat / USD)": "Unit Price (Fiat / USD)", + "Set 7 for CNY or 1 for USD per 1 USD balance.": "Set 7 for CNY or 1 for USD per 1 USD balance.", + "Minimum Top-up (USD)": "Minimum Top-up (USD)", + "Order Timeout (Seconds)": "Order Timeout (Seconds)", + "Default 600s (0 uses BEpusdt default).": "Default 600s (0 uses BEpusdt default).", + "Custom Webhook URL (Optional)": "Custom Webhook URL (Optional)", + "Leave blank to automatically use ServerAddress / CustomCallbackAddress + /api/bepusdt/webhook.": "Leave blank to automatically use ServerAddress / CustomCallbackAddress + /api/bepusdt/webhook.", + "Custom Return URL (Optional)": "Custom Return URL (Optional)", + "Leave blank to return users to the wallet order history page.": "Leave blank to return users to the wallet order history page.", + "Cryptocurrency payment is not enabled": "Cryptocurrency payment is not enabled", + "Failed to create payment order": "Failed to create payment order", + "Server address is not configured": "Server address is not configured", + "BEpusdt Admin Console": "BEpusdt Admin Console", + "Configure the BEpusdt Admin Login URL below to quickly open the console.": "Configure the BEpusdt Admin Login URL below to quickly open the console.", + "Open BEpusdt Admin": "Open BEpusdt Admin", + "BEpusdt Admin Login URL": "BEpusdt Admin Login URL", + "Full BEpusdt admin login URL including the security entry path for quick access.": "Full BEpusdt admin login URL including the security entry path for quick access." } } diff --git a/web/src/i18n/locales/ru.json b/web/src/i18n/locales/ru.json index b2aa664..71ac877 100644 --- a/web/src/i18n/locales/ru.json +++ b/web/src/i18n/locales/ru.json @@ -2965,7 +2965,7 @@ "footer.columns.related.links.oneApi": "Один API", "footer.columns.related.title": "Связанные проекты", "footer.defaultCopyright": "Все права защищены.", - "footer.new\u0061pi.projectAttributionSuffix": "Все права защищены. Разработано участниками проекта.", + "footer.newapi.projectAttributionSuffix": "Все права защищены. Разработано участниками проекта.", "For a stronger password": "Чтобы сделать пароль надёжнее", "For advanced custom channels this applies only to /v1/responses routes without protocol conversion.": "Для расширенных пользовательских каналов это действует только для маршрутов /v1/responses без преобразования протокола.", "For channels added after May 10, 2025, no need to remove \".\" from model names during deployment": "Для каналов, добавленных после 10 мая 2025 г., не нужно удалять \".\" из имён моделей при развёртывании", @@ -7757,6 +7757,52 @@ "Zhipu V4": "Zhipu V4", "Zoom": "Zoom", "By clicking sign in, you agree to our": "Нажимая «Войти», вы соглашаетесь с нашими", - "By creating an account, you agree to our": "Создавая аккаунт, вы соглашаетесь с нашими" + "By creating an account, you agree to our": "Создавая аккаунт, вы соглашаетесь с нашими", + "Cryptocurrency": "Cryptocurrency", + "Cryptocurrency (USDT)": "Cryptocurrency (USDT)", + "Cryptocurrency Payment Gateway (BEpusdt)": "Cryptocurrency Payment Gateway (BEpusdt)", + "Accept USDT, USDC, TRX and other crypto payments via BEpusdt without affecting Epay settings.": "Accept USDT, USDC, TRX and other crypto payments via BEpusdt without affecting Epay settings.", + "API Token Configured": "API Token Configured", + "API Token Not Configured": "API Token Not Configured", + "Obtain the API URL and API Token from BEpusdt Admin -> System -> Basic Settings -> API Settings.": "Obtain the API URL and API Token from BEpusdt Admin -> System -> Basic Settings -> API Settings.", + "Default webhook callback URL:": "Default webhook callback URL:", + "Enable Cryptocurrency Payment (BEpusdt)": "Enable Cryptocurrency Payment (BEpusdt)", + "Display the cryptocurrency payment method on the wallet top-up page.": "Display the cryptocurrency payment method on the wallet top-up page.", + "BEpusdt API URL": "BEpusdt API URL", + "Base URL of your BEpusdt instance without trailing slash.": "Base URL of your BEpusdt instance without trailing slash.", + "BEpusdt API Token": "BEpusdt API Token", + "Configured — leave blank to keep unchanged": "Configured — leave blank to keep unchanged", + "Enter BEpusdt API Token": "Enter BEpusdt API Token", + "Used to sign requests and verify payment callbacks.": "Used to sign requests and verify payment callbacks.", + "Checkout Mode": "Checkout Mode", + "Cashier Mode (User chooses coin & network)": "Cashier Mode (User chooses coin & network)", + "Fixed Trade Type (create-transaction)": "Fixed Trade Type (create-transaction)", + "Calls /api/v1/order/create-transaction with a fixed trade type.": "Calls /api/v1/order/create-transaction with a fixed trade type.", + "Calls /api/v1/order/create-order so users can select USDT/USDC/TRX and network on the checkout page.": "Calls /api/v1/order/create-order so users can select USDT/USDC/TRX and network on the checkout page.", + "Payment method label shown to users on the wallet page.": "Payment method label shown to users on the wallet page.", + "Trade Type": "Trade Type", + "Must match an enabled wallet network in BEpusdt.": "Must match an enabled wallet network in BEpusdt.", + "Forced Exchange Rate (Optional)": "Forced Exchange Rate (Optional)", + "Leave blank to use BEpusdt configured exchange rate.": "Leave blank to use BEpusdt configured exchange rate.", + "Allowed Currencies (Optional)": "Allowed Currencies (Optional)", + "Comma-separated currencies (e.g. USDT,USDC or -ETH,-BNB). Leave blank to allow all enabled currencies in BEpusdt.": "Comma-separated currencies (e.g. USDT,USDC or -ETH,-BNB). Leave blank to allow all enabled currencies in BEpusdt.", + "Fiat Currency": "Fiat Currency", + "Unit Price (Fiat / USD)": "Unit Price (Fiat / USD)", + "Set 7 for CNY or 1 for USD per 1 USD balance.": "Set 7 for CNY or 1 for USD per 1 USD balance.", + "Minimum Top-up (USD)": "Minimum Top-up (USD)", + "Order Timeout (Seconds)": "Order Timeout (Seconds)", + "Default 600s (0 uses BEpusdt default).": "Default 600s (0 uses BEpusdt default).", + "Custom Webhook URL (Optional)": "Custom Webhook URL (Optional)", + "Leave blank to automatically use ServerAddress / CustomCallbackAddress + /api/bepusdt/webhook.": "Leave blank to automatically use ServerAddress / CustomCallbackAddress + /api/bepusdt/webhook.", + "Custom Return URL (Optional)": "Custom Return URL (Optional)", + "Leave blank to return users to the wallet order history page.": "Leave blank to return users to the wallet order history page.", + "Cryptocurrency payment is not enabled": "Cryptocurrency payment is not enabled", + "Failed to create payment order": "Failed to create payment order", + "Server address is not configured": "Server address is not configured", + "BEpusdt Admin Console": "BEpusdt Admin Console", + "Configure the BEpusdt Admin Login URL below to quickly open the console.": "Configure the BEpusdt Admin Login URL below to quickly open the console.", + "Open BEpusdt Admin": "Open BEpusdt Admin", + "BEpusdt Admin Login URL": "BEpusdt Admin Login URL", + "Full BEpusdt admin login URL including the security entry path for quick access.": "Full BEpusdt admin login URL including the security entry path for quick access." } } diff --git a/web/src/i18n/locales/vi.json b/web/src/i18n/locales/vi.json index 5771724..8f12c08 100644 --- a/web/src/i18n/locales/vi.json +++ b/web/src/i18n/locales/vi.json @@ -2965,7 +2965,7 @@ "footer.columns.related.links.oneApi": "One API", "footer.columns.related.title": "Các Dự Án Liên Quan", "footer.defaultCopyright": "Bản quyền được bảo lưu.", - "footer.new\u0061pi.projectAttributionSuffix": "Bản quyền được bảo lưu. Được thiết kế và phát triển bởi các cộng tác viên dự án.", + "footer.newapi.projectAttributionSuffix": "Bản quyền được bảo lưu. Được thiết kế và phát triển bởi các cộng tác viên dự án.", "For a stronger password": "Để mật khẩu mạnh hơn", "For advanced custom channels this applies only to /v1/responses routes without protocol conversion.": "Với kênh tùy chỉnh nâng cao, thiết lập này chỉ áp dụng cho các route /v1/responses không chuyển đổi giao thức.", "For channels added after May 10, 2025, no need to remove \".\" from model names during deployment": "Đối với các kênh được thêm sau ngày 10 tháng 5 năm 2025, không cần loại bỏ \".\" khỏi tên mô hình trong quá trình triển khai", @@ -7757,6 +7757,52 @@ "Zhipu V4": "Zhipu V4", "Zoom": "Zoom", "By clicking sign in, you agree to our": "Bằng cách nhấp đăng nhập, bạn đồng ý với", - "By creating an account, you agree to our": "Bằng cách tạo tài khoản, bạn đồng ý với" + "By creating an account, you agree to our": "Bằng cách tạo tài khoản, bạn đồng ý với", + "Cryptocurrency": "Cryptocurrency", + "Cryptocurrency (USDT)": "Cryptocurrency (USDT)", + "Cryptocurrency Payment Gateway (BEpusdt)": "Cryptocurrency Payment Gateway (BEpusdt)", + "Accept USDT, USDC, TRX and other crypto payments via BEpusdt without affecting Epay settings.": "Accept USDT, USDC, TRX and other crypto payments via BEpusdt without affecting Epay settings.", + "API Token Configured": "API Token Configured", + "API Token Not Configured": "API Token Not Configured", + "Obtain the API URL and API Token from BEpusdt Admin -> System -> Basic Settings -> API Settings.": "Obtain the API URL and API Token from BEpusdt Admin -> System -> Basic Settings -> API Settings.", + "Default webhook callback URL:": "Default webhook callback URL:", + "Enable Cryptocurrency Payment (BEpusdt)": "Enable Cryptocurrency Payment (BEpusdt)", + "Display the cryptocurrency payment method on the wallet top-up page.": "Display the cryptocurrency payment method on the wallet top-up page.", + "BEpusdt API URL": "BEpusdt API URL", + "Base URL of your BEpusdt instance without trailing slash.": "Base URL of your BEpusdt instance without trailing slash.", + "BEpusdt API Token": "BEpusdt API Token", + "Configured — leave blank to keep unchanged": "Configured — leave blank to keep unchanged", + "Enter BEpusdt API Token": "Enter BEpusdt API Token", + "Used to sign requests and verify payment callbacks.": "Used to sign requests and verify payment callbacks.", + "Checkout Mode": "Checkout Mode", + "Cashier Mode (User chooses coin & network)": "Cashier Mode (User chooses coin & network)", + "Fixed Trade Type (create-transaction)": "Fixed Trade Type (create-transaction)", + "Calls /api/v1/order/create-transaction with a fixed trade type.": "Calls /api/v1/order/create-transaction with a fixed trade type.", + "Calls /api/v1/order/create-order so users can select USDT/USDC/TRX and network on the checkout page.": "Calls /api/v1/order/create-order so users can select USDT/USDC/TRX and network on the checkout page.", + "Payment method label shown to users on the wallet page.": "Payment method label shown to users on the wallet page.", + "Trade Type": "Trade Type", + "Must match an enabled wallet network in BEpusdt.": "Must match an enabled wallet network in BEpusdt.", + "Forced Exchange Rate (Optional)": "Forced Exchange Rate (Optional)", + "Leave blank to use BEpusdt configured exchange rate.": "Leave blank to use BEpusdt configured exchange rate.", + "Allowed Currencies (Optional)": "Allowed Currencies (Optional)", + "Comma-separated currencies (e.g. USDT,USDC or -ETH,-BNB). Leave blank to allow all enabled currencies in BEpusdt.": "Comma-separated currencies (e.g. USDT,USDC or -ETH,-BNB). Leave blank to allow all enabled currencies in BEpusdt.", + "Fiat Currency": "Fiat Currency", + "Unit Price (Fiat / USD)": "Unit Price (Fiat / USD)", + "Set 7 for CNY or 1 for USD per 1 USD balance.": "Set 7 for CNY or 1 for USD per 1 USD balance.", + "Minimum Top-up (USD)": "Minimum Top-up (USD)", + "Order Timeout (Seconds)": "Order Timeout (Seconds)", + "Default 600s (0 uses BEpusdt default).": "Default 600s (0 uses BEpusdt default).", + "Custom Webhook URL (Optional)": "Custom Webhook URL (Optional)", + "Leave blank to automatically use ServerAddress / CustomCallbackAddress + /api/bepusdt/webhook.": "Leave blank to automatically use ServerAddress / CustomCallbackAddress + /api/bepusdt/webhook.", + "Custom Return URL (Optional)": "Custom Return URL (Optional)", + "Leave blank to return users to the wallet order history page.": "Leave blank to return users to the wallet order history page.", + "Cryptocurrency payment is not enabled": "Cryptocurrency payment is not enabled", + "Failed to create payment order": "Failed to create payment order", + "Server address is not configured": "Server address is not configured", + "BEpusdt Admin Console": "BEpusdt Admin Console", + "Configure the BEpusdt Admin Login URL below to quickly open the console.": "Configure the BEpusdt Admin Login URL below to quickly open the console.", + "Open BEpusdt Admin": "Open BEpusdt Admin", + "BEpusdt Admin Login URL": "BEpusdt Admin Login URL", + "Full BEpusdt admin login URL including the security entry path for quick access.": "Full BEpusdt admin login URL including the security entry path for quick access." } } diff --git a/web/src/i18n/locales/zh-TW.json b/web/src/i18n/locales/zh-TW.json index b7c5131..507aea0 100644 --- a/web/src/i18n/locales/zh-TW.json +++ b/web/src/i18n/locales/zh-TW.json @@ -2965,7 +2965,7 @@ "footer.columns.related.links.oneApi": "One API", "footer.columns.related.title": "相關項目", "footer.defaultCopyright": "版權所有。", - "footer.new\u0061pi.projectAttributionSuffix": "版權所有,由項目貢獻者設計與開發。", + "footer.newapi.projectAttributionSuffix": "版權所有,由項目貢獻者設計與開發。", "For a stronger password": "讓密碼更強", "For advanced custom channels this applies only to /v1/responses routes without protocol conversion.": "進階自訂渠道僅對 /v1/responses 且不做協定轉換的路由生效。", "For channels added after May 10, 2025, no need to remove \".\" from model names during deployment": "對於 2025 年 5 月 10 日之後新增的渠道,在部署時無需從模型名稱中移除 \".\"", @@ -7757,6 +7757,52 @@ "Zhipu V4": "智譜 V4", "Zoom": "縮放", "By clicking sign in, you agree to our": "點擊登入即表示您同意我們的", - "By creating an account, you agree to our": "建立帳戶即表示您同意我們的" + "By creating an account, you agree to our": "建立帳戶即表示您同意我們的", + "Cryptocurrency": "數字貨幣", + "Cryptocurrency (USDT)": "數字貨幣 (USDT)", + "Cryptocurrency Payment Gateway (BEpusdt)": "數字貨幣支付網關 (BEpusdt)", + "Accept USDT, USDC, TRX and other crypto payments via BEpusdt without affecting Epay settings.": "透過 BEpusdt 接收 USDT、USDC、TRX 等數字貨幣支付,與易支付設定完全獨立、互不影響。", + "API Token Configured": "API Token 已設定", + "API Token Not Configured": "API Token 未設定", + "Obtain the API URL and API Token from BEpusdt Admin -> System -> Basic Settings -> API Settings.": "請在 BEpusdt 後台 → 系統管理 → 基本設定 → API 設定中取得介面位址與對接權杖。", + "Default webhook callback URL:": "預設非同步回呼網址:", + "Enable Cryptocurrency Payment (BEpusdt)": "啟用數字貨幣支付 (BEpusdt)", + "Display the cryptocurrency payment method on the wallet top-up page.": "開啟後將在使用者錢包儲值頁顯示數字貨幣支付方式。", + "BEpusdt API URL": "BEpusdt 介面位址", + "Base URL of your BEpusdt instance without trailing slash.": "BEpusdt 服務位址(如 https://pay.example.com),結尾無須斜線。", + "BEpusdt API Token": "BEpusdt 對接權杖 (API Token)", + "Configured — leave blank to keep unchanged": "已設定,留空保持不變", + "Enter BEpusdt API Token": "請輸入 BEpusdt API Token", + "Used to sign requests and verify payment callbacks.": "用於請求簽章與支付非同步回呼驗簽。", + "Checkout Mode": "下單模式", + "Cashier Mode (User chooses coin & network)": "收銀台自選模式(使用者於付款頁自選幣種/網路)", + "Fixed Trade Type (create-transaction)": "固定交易類型模式(create-transaction)", + "Calls /api/v1/order/create-transaction with a fixed trade type.": "呼叫 /api/v1/order/create-transaction,依下方固定交易類型建立訂單。", + "Calls /api/v1/order/create-order so users can select USDT/USDC/TRX and network on the checkout page.": "呼叫 /api/v1/order/create-order,使用者可在 BEpusdt 收銀台自由選擇 USDT/USDC/TRX 與鏈網路。", + "Payment method label shown to users on the wallet page.": "在使用者錢包儲值頁顯示的支付方式名稱(留空預設「數字貨幣」)。", + "Trade Type": "交易類型 (trade_type)", + "Must match an enabled wallet network in BEpusdt.": "須確保 BEpusdt 後台已新增並啟用對應網路錢包位址。", + "Forced Exchange Rate (Optional)": "強制匯率(選填)", + "Leave blank to use BEpusdt configured exchange rate.": "支援固定匯率如 7.4、浮動如 ~1.02 或 +0.3;留空使用 BEpusdt 預設匯率。", + "Allowed Currencies (Optional)": "限定交易幣種(選填)", + "Comma-separated currencies (e.g. USDT,USDC or -ETH,-BNB). Leave blank to allow all enabled currencies in BEpusdt.": "多個幣種以英文逗號分隔,如 USDT,USDC 或黑名單 -ETH,-BNB;留空則允許 BEpusdt 已啟用的全部幣種。", + "Fiat Currency": "計價法幣", + "Unit Price (Fiat / USD)": "兌換單價(法幣 / 美元額度)", + "Set 7 for CNY or 1 for USD per 1 USD balance.": "每 1 美元站內額度對應的法幣價格(如法幣為 CNY 填 7,為 USD 填 1)。", + "Minimum Top-up (USD)": "最低儲值金額(美元)", + "Order Timeout (Seconds)": "訂單逾時時間(秒)", + "Default 600s (0 uses BEpusdt default).": "預設 600 秒(填 0 使用 BEpusdt 後台預設設定)。", + "Custom Webhook URL (Optional)": "自訂非同步回呼網址(選填)", + "Leave blank to automatically use ServerAddress / CustomCallbackAddress + /api/bepusdt/webhook.": "留空則自動使用伺服器位址或自訂回呼網域 + /api/bepusdt/webhook。", + "Custom Return URL (Optional)": "自訂支付成功跳轉網址(選填)", + "Leave blank to return users to the wallet order history page.": "留空則支付完成後自動跳回使用者錢包儲值紀錄頁。", + "Cryptocurrency payment is not enabled": "數字貨幣支付未啟用", + "Failed to create payment order": "建立支付訂單失敗", + "Server address is not configured": "伺服器位址未設定", + "BEpusdt Admin Console": "BEpusdt 管理後台入口", + "Configure the BEpusdt Admin Login URL below to quickly open the console.": "請在下方填寫 BEpusdt 後台登入網址,儲存後可一鍵直達管理後台。", + "Open BEpusdt Admin": "進入 BEpusdt 後台", + "BEpusdt Admin Login URL": "BEpusdt 後台登入網址", + "Full BEpusdt admin login URL including the security entry path for quick access.": "包含安全入口路徑的完整 BEpusdt 後台登入網址,便於從此處快速進入管理後台。" } } diff --git a/web/src/i18n/locales/zh.json b/web/src/i18n/locales/zh.json index c45ccd1..43cdb1d 100644 --- a/web/src/i18n/locales/zh.json +++ b/web/src/i18n/locales/zh.json @@ -2965,7 +2965,7 @@ "footer.columns.related.links.oneApi": "One API", "footer.columns.related.title": "相关项目", "footer.defaultCopyright": "版权所有。", - "footer.new\u0061pi.projectAttributionSuffix": "版权所有,由项目贡献者设计与开发。", + "footer.newapi.projectAttributionSuffix": "版权所有,由项目贡献者设计与开发。", "For a stronger password": "让密码更强", "For advanced custom channels this applies only to /v1/responses routes without protocol conversion.": "高级自定义渠道仅对 /v1/responses 且不做协议转换的路由生效。", "For channels added after May 10, 2025, no need to remove \".\" from model names during deployment": "对于 2025 年 5 月 10 日之后添加的渠道,在部署时无需从模型名称中移除 \".\"", @@ -7757,6 +7757,52 @@ "Zhipu V4": "智谱 V4", "Zoom": "缩放", "By clicking sign in, you agree to our": "点击登录即表示您同意我们的", - "By creating an account, you agree to our": "创建账户即表示您同意我们的" + "By creating an account, you agree to our": "创建账户即表示您同意我们的", + "Cryptocurrency": "数字货币", + "Cryptocurrency (USDT)": "数字货币 (USDT)", + "Cryptocurrency Payment Gateway (BEpusdt)": "数字货币支付网关 (BEpusdt)", + "Accept USDT, USDC, TRX and other crypto payments via BEpusdt without affecting Epay settings.": "通过 BEpusdt 接收 USDT、USDC、TRX 等数字货币支付,与易支付配置完全独立、互不影响。", + "API Token Configured": "API Token 已配置", + "API Token Not Configured": "API Token 未配置", + "Obtain the API URL and API Token from BEpusdt Admin -> System -> Basic Settings -> API Settings.": "请在 BEpusdt 后台 → 系统管理 → 基本设置 → API 设置中获取接口地址与对接令牌。", + "Default webhook callback URL:": "默认异步回调地址:", + "Enable Cryptocurrency Payment (BEpusdt)": "启用数字货币支付 (BEpusdt)", + "Display the cryptocurrency payment method on the wallet top-up page.": "开启后将在用户钱包充值页展示数字货币支付方式。", + "BEpusdt API URL": "BEpusdt 接口地址", + "Base URL of your BEpusdt instance without trailing slash.": "BEpusdt 服务地址(如 https://pay.example.com),末尾无需斜杠。", + "BEpusdt API Token": "BEpusdt 对接令牌 (API Token)", + "Configured — leave blank to keep unchanged": "已配置,留空保持不变", + "Enter BEpusdt API Token": "请输入 BEpusdt API Token", + "Used to sign requests and verify payment callbacks.": "用于请求签名与支付异步回调验签。", + "Checkout Mode": "下单模式", + "Cashier Mode (User chooses coin & network)": "收银台自选模式(用户在付款页自选币种/网络)", + "Fixed Trade Type (create-transaction)": "固定交易类型模式(create-transaction)", + "Calls /api/v1/order/create-transaction with a fixed trade type.": "调用 /api/v1/order/create-transaction,按下方固定交易类型创建订单。", + "Calls /api/v1/order/create-order so users can select USDT/USDC/TRX and network on the checkout page.": "调用 /api/v1/order/create-order,用户可在 BEpusdt 收银台自由选择 USDT/USDC/TRX 与链网络。", + "Payment method label shown to users on the wallet page.": "在用户钱包充值页显示的支付方式名称(留空默认“数字货币”)。", + "Trade Type": "交易类型 (trade_type)", + "Must match an enabled wallet network in BEpusdt.": "需确保 BEpusdt 后台已添加并启用对应网络钱包地址。", + "Forced Exchange Rate (Optional)": "强制汇率(可选)", + "Leave blank to use BEpusdt configured exchange rate.": "支持固定汇率如 7.4、浮动如 ~1.02 或 +0.3;留空使用 BEpusdt 默认汇率。", + "Allowed Currencies (Optional)": "限定交易币种(可选)", + "Comma-separated currencies (e.g. USDT,USDC or -ETH,-BNB). Leave blank to allow all enabled currencies in BEpusdt.": "多个币种用英文逗号分隔,如 USDT,USDC 或黑名单 -ETH,-BNB;留空则允许 BEpusdt 已启用的全部币种。", + "Fiat Currency": "计价法币", + "Unit Price (Fiat / USD)": "兑换单价(法币 / 美元额度)", + "Set 7 for CNY or 1 for USD per 1 USD balance.": "每 1 美元站内额度对应的法币价格(如法币为 CNY 填 7,为 USD 填 1)。", + "Minimum Top-up (USD)": "最低充值金额(美元)", + "Order Timeout (Seconds)": "订单超时时间(秒)", + "Default 600s (0 uses BEpusdt default).": "默认 600 秒(填 0 使用 BEpusdt 后台默认配置)。", + "Custom Webhook URL (Optional)": "自定义异步回调地址(可选)", + "Leave blank to automatically use ServerAddress / CustomCallbackAddress + /api/bepusdt/webhook.": "留空则自动使用服务器地址或自定义回调域名 + /api/bepusdt/webhook。", + "Custom Return URL (Optional)": "自定义支付成功跳转地址(可选)", + "Leave blank to return users to the wallet order history page.": "留空则支付完成后自动跳回用户钱包充值记录页。", + "Cryptocurrency payment is not enabled": "数字货币支付未启用", + "Failed to create payment order": "创建支付订单失败", + "Server address is not configured": "服务器地址未配置", + "BEpusdt Admin Console": "BEpusdt 管理后台入口", + "Configure the BEpusdt Admin Login URL below to quickly open the console.": "请在下方填写 BEpusdt 后台登录地址,保存后可一键直达管理后台。", + "Open BEpusdt Admin": "进入 BEpusdt 后台", + "BEpusdt Admin Login URL": "BEpusdt 后台登录地址", + "Full BEpusdt admin login URL including the security entry path for quick access.": "包含安全入口路径的完整 BEpusdt 后台登录地址,便于从此处快速进入管理后台。" } }