diff --git a/controller/payment_webhook_availability.go b/controller/payment_webhook_availability.go index 9e7a08aea08..9bc0f59d606 100644 --- a/controller/payment_webhook_availability.go +++ b/controller/payment_webhook_availability.go @@ -7,8 +7,23 @@ import ( "github.com/QuantumNous/new-api/setting/operation_setting" ) +func getStripeAPISecret() string { + return strings.TrimSpace(setting.StripeApiSecret) +} + +func isStripeAPISecretConfigured() bool { + key := getStripeAPISecret() + return strings.HasPrefix(key, "sk_") || strings.HasPrefix(key, "rk_") +} + +func isStripeLiveMode() bool { + key := getStripeAPISecret() + return strings.HasPrefix(key, "sk_live_") || strings.HasPrefix(key, "rk_live_") +} + func isStripeTopUpEnabled() bool { - return strings.TrimSpace(setting.StripeApiSecret) != "" && + return setting.StripeEnabled && + isStripeAPISecretConfigured() && strings.TrimSpace(setting.StripeWebhookSecret) != "" && strings.TrimSpace(setting.StripePriceId) != "" } @@ -18,7 +33,7 @@ func isStripeWebhookConfigured() bool { } func isStripeWebhookEnabled() bool { - return isStripeTopUpEnabled() + return isStripeWebhookConfigured() } func isCreemTopUpEnabled() bool { diff --git a/controller/payment_webhook_availability_test.go b/controller/payment_webhook_availability_test.go index 0534acc45f3..13321edca37 100644 --- a/controller/payment_webhook_availability_test.go +++ b/controller/payment_webhook_availability_test.go @@ -8,16 +8,19 @@ import ( "github.com/stretchr/testify/require" ) -func TestStripeWebhookEnabledRequiresTopUpAndWebhookConfig(t *testing.T) { +func TestStripeWebhookEnabledRequiresWebhookConfig(t *testing.T) { originalAPISecret := setting.StripeApiSecret originalWebhookSecret := setting.StripeWebhookSecret originalPriceID := setting.StripePriceId + originalEnabled := setting.StripeEnabled t.Cleanup(func() { setting.StripeApiSecret = originalAPISecret setting.StripeWebhookSecret = originalWebhookSecret setting.StripePriceId = originalPriceID + setting.StripeEnabled = originalEnabled }) + setting.StripeEnabled = true setting.StripeWebhookSecret = "" setting.StripeApiSecret = "sk_test_123" setting.StripePriceId = "price_123" @@ -27,7 +30,33 @@ func TestStripeWebhookEnabledRequiresTopUpAndWebhookConfig(t *testing.T) { require.True(t, isStripeWebhookEnabled()) setting.StripePriceId = "" - require.False(t, isStripeWebhookEnabled()) + require.True(t, isStripeWebhookEnabled()) + + setting.StripePriceId = "price_123" + setting.StripeEnabled = false + require.True(t, isStripeWebhookEnabled()) +} + +func TestStripeTopUpEnabledRequiresExplicitEnable(t *testing.T) { + originalAPISecret := setting.StripeApiSecret + originalWebhookSecret := setting.StripeWebhookSecret + originalPriceID := setting.StripePriceId + originalEnabled := setting.StripeEnabled + t.Cleanup(func() { + setting.StripeApiSecret = originalAPISecret + setting.StripeWebhookSecret = originalWebhookSecret + setting.StripePriceId = originalPriceID + setting.StripeEnabled = originalEnabled + }) + + setting.StripeApiSecret = "sk_test_123" + setting.StripeWebhookSecret = "whsec_test" + setting.StripePriceId = "price_123" + setting.StripeEnabled = true + require.True(t, isStripeTopUpEnabled()) + + setting.StripeEnabled = false + require.False(t, isStripeTopUpEnabled()) } func TestCreemWebhookEnabledRequiresTopUpAndWebhookConfig(t *testing.T) { diff --git a/controller/subscription_payment_stripe.go b/controller/subscription_payment_stripe.go index a5ce4685b4c..fbace1a7248 100644 --- a/controller/subscription_payment_stripe.go +++ b/controller/subscription_payment_stripe.go @@ -3,7 +3,6 @@ package controller import ( "fmt" "net/http" - "strings" "time" "github.com/QuantumNous/new-api/common" @@ -41,7 +40,11 @@ func SubscriptionRequestStripePay(c *gin.Context) { common.ApiErrorMsg(c, "该套餐未配置 StripePriceId") return } - if !strings.HasPrefix(setting.StripeApiSecret, "sk_") && !strings.HasPrefix(setting.StripeApiSecret, "rk_") { + if !setting.StripeEnabled { + common.ApiErrorMsg(c, "Stripe 未启用") + return + } + if !isStripeAPISecretConfigured() { common.ApiErrorMsg(c, "Stripe 未配置或密钥无效") return } @@ -76,7 +79,9 @@ func SubscriptionRequestStripePay(c *gin.Context) { reference := fmt.Sprintf("sub-stripe-ref-%d-%d-%s", user.Id, time.Now().UnixMilli(), randstr.String(4)) referenceId := "sub_ref_" + common.Sha1([]byte(reference)) - payLink, err := genStripeSubscriptionLink(referenceId, user.StripeCustomer, user.Email, plan.StripePriceId) + stripeLiveMode := isStripeLiveMode() + customerId := model.GetStripeCustomerID(user, stripeLiveMode) + payLink, err := genStripeSubscriptionLink(referenceId, customerId, user.Email, plan.StripePriceId) if err != nil { logger.LogError(c.Request.Context(), fmt.Sprintf("Stripe 订阅支付链接创建失败 trade_no=%s plan_id=%d error=%q", referenceId, plan.Id, err.Error())) c.JSON(http.StatusOK, gin.H{"message": "error", "data": "拉起支付失败"}) @@ -107,7 +112,7 @@ func SubscriptionRequestStripePay(c *gin.Context) { } func genStripeSubscriptionLink(referenceId string, customerId string, email string, priceId string) (string, error) { - stripe.Key = setting.StripeApiSecret + stripe.Key = getStripeAPISecret() params := &stripe.CheckoutSessionParams{ ClientReferenceID: stripe.String(referenceId), diff --git a/controller/topup_stripe.go b/controller/topup_stripe.go index ceee8ecdd66..8226b37b31b 100644 --- a/controller/topup_stripe.go +++ b/controller/topup_stripe.go @@ -44,6 +44,10 @@ type StripeAdaptor struct { } func (*StripeAdaptor) RequestAmount(c *gin.Context, req *StripePayRequest) { + if !isStripeTopUpEnabled() { + c.JSON(http.StatusOK, gin.H{"message": "error", "data": "Stripe 未启用"}) + return + } if req.Amount < getStripeMinTopup() { c.JSON(http.StatusOK, gin.H{"message": "error", "data": fmt.Sprintf("充值数量不能小于 %d", getStripeMinTopup())}) return @@ -63,6 +67,10 @@ func (*StripeAdaptor) RequestAmount(c *gin.Context, req *StripePayRequest) { } func (*StripeAdaptor) RequestPay(c *gin.Context, req *StripePayRequest) { + if !isStripeTopUpEnabled() { + c.JSON(http.StatusOK, gin.H{"message": "error", "data": "Stripe 未启用"}) + return + } if req.PaymentMethod != model.PaymentMethodStripe { c.JSON(http.StatusOK, gin.H{"message": "error", "data": "不支持的支付渠道"}) return @@ -93,7 +101,9 @@ func (*StripeAdaptor) RequestPay(c *gin.Context, req *StripePayRequest) { reference := fmt.Sprintf("new-api-ref-%d-%d-%s", user.Id, time.Now().UnixMilli(), randstr.String(4)) referenceId := "ref_" + common.Sha1([]byte(reference)) - payLink, err := genStripeLink(referenceId, user.StripeCustomer, user.Email, req.Amount, req.SuccessURL, req.CancelURL) + stripeLiveMode := isStripeLiveMode() + customerId := model.GetStripeCustomerID(user, stripeLiveMode) + payLink, err := genStripeLink(referenceId, customerId, user.Email, req.Amount, req.SuccessURL, req.CancelURL) if err != nil { logger.LogError(c.Request.Context(), fmt.Sprintf("Stripe 创建 Checkout Session 失败 user_id=%d trade_no=%s amount=%d error=%q", id, referenceId, req.Amount, err.Error())) c.JSON(http.StatusOK, gin.H{"message": "error", "data": "拉起支付失败"}) @@ -270,8 +280,9 @@ func fulfillOrder(ctx context.Context, event stripe.Event, referenceId string, c "amount_total": event.GetObjectValue("amount_total"), "currency": strings.ToUpper(event.GetObjectValue("currency")), "event_type": string(event.Type), + "livemode": event.Livemode, } - if err := model.CompleteSubscriptionOrder(referenceId, common.GetJsonString(payload), model.PaymentProviderStripe, ""); err == nil { + if err := model.CompleteStripeSubscriptionOrder(referenceId, common.GetJsonString(payload), customerId, event.Livemode); err == nil { logger.LogInfo(ctx, fmt.Sprintf("Stripe 订阅订单处理成功 trade_no=%s event_type=%s client_ip=%s", referenceId, string(event.Type), callerIp)) return } else if err != nil && !errors.Is(err, model.ErrSubscriptionOrderNotFound) { @@ -279,7 +290,7 @@ func fulfillOrder(ctx context.Context, event stripe.Event, referenceId string, c return } - err := model.Recharge(referenceId, customerId, callerIp) + err := model.Recharge(referenceId, customerId, event.Livemode, callerIp) if err != nil { logger.LogError(ctx, fmt.Sprintf("Stripe 充值处理失败 trade_no=%s event_type=%s client_ip=%s error=%q", referenceId, string(event.Type), callerIp, err.Error())) return @@ -340,11 +351,11 @@ func sessionExpired(ctx context.Context, event stripe.Event) { // // Returns the checkout session URL or an error if the session creation fails. func genStripeLink(referenceId string, customerId string, email string, amount int64, successURL string, cancelURL string) (string, error) { - if !strings.HasPrefix(setting.StripeApiSecret, "sk_") && !strings.HasPrefix(setting.StripeApiSecret, "rk_") { + if !isStripeAPISecretConfigured() { return "", fmt.Errorf("无效的Stripe API密钥") } - stripe.Key = setting.StripeApiSecret + stripe.Key = getStripeAPISecret() // Use custom URLs if provided, otherwise use defaults if successURL == "" { diff --git a/model/db_time.go b/model/db_time.go index dca14292d39..09ce053635a 100644 --- a/model/db_time.go +++ b/model/db_time.go @@ -1,19 +1,30 @@ package model -import "github.com/QuantumNous/new-api/common" +import ( + "github.com/QuantumNous/new-api/common" + "gorm.io/gorm" +) // GetDBTimestamp returns a UNIX timestamp from database time. // Falls back to application time on error. func GetDBTimestamp() int64 { + return GetDBTimestampTx(nil) +} + +func GetDBTimestampTx(tx *gorm.DB) int64 { var ts int64 var err error + query := DB + if tx != nil { + query = tx + } switch { case common.UsingPostgreSQL: - err = DB.Raw("SELECT EXTRACT(EPOCH FROM NOW())::bigint").Scan(&ts).Error + err = query.Raw("SELECT EXTRACT(EPOCH FROM NOW())::bigint").Scan(&ts).Error case common.UsingSQLite: - err = DB.Raw("SELECT strftime('%s','now')").Scan(&ts).Error + err = query.Raw("SELECT strftime('%s','now')").Scan(&ts).Error default: - err = DB.Raw("SELECT UNIX_TIMESTAMP()").Scan(&ts).Error + err = query.Raw("SELECT UNIX_TIMESTAMP()").Scan(&ts).Error } if err != nil || ts <= 0 { return common.GetTimestamp() diff --git a/model/option.go b/model/option.go index e0a3048d34f..26aa6deca27 100644 --- a/model/option.go +++ b/model/option.go @@ -86,6 +86,7 @@ func InitOptionMap() { common.OptionMap["StripePriceId"] = setting.StripePriceId common.OptionMap["StripeUnitPrice"] = strconv.FormatFloat(setting.StripeUnitPrice, 'f', -1, 64) common.OptionMap["StripePromotionCodesEnabled"] = strconv.FormatBool(setting.StripePromotionCodesEnabled) + common.OptionMap["StripeEnabled"] = strconv.FormatBool(setting.StripeEnabled) common.OptionMap["CreemApiKey"] = setting.CreemApiKey common.OptionMap["CreemProducts"] = setting.CreemProducts common.OptionMap["CreemTestMode"] = strconv.FormatBool(setting.CreemTestMode) @@ -381,6 +382,8 @@ func updateOptionMap(key string, value string) (err error) { setting.StripeMinTopUp, _ = strconv.Atoi(value) case "StripePromotionCodesEnabled": setting.StripePromotionCodesEnabled = value == "true" + case "StripeEnabled": + setting.StripeEnabled = value == "true" case "CreemApiKey": setting.CreemApiKey = value case "CreemProducts": diff --git a/model/stripe_customer_test.go b/model/stripe_customer_test.go new file mode 100644 index 00000000000..1215eb1a787 --- /dev/null +++ b/model/stripe_customer_test.go @@ -0,0 +1,89 @@ +package model + +import ( + "testing" + "time" + + "github.com/QuantumNous/new-api/common" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestGetStripeCustomerIDSeparatesLiveAndTest(t *testing.T) { + user := &User{ + StripeCustomer: "cus_legacy", + StripeCustomerTest: "cus_test", + StripeCustomerLive: "cus_live", + } + + assert.Equal(t, "cus_live", GetStripeCustomerID(user, true)) + assert.Equal(t, "cus_test", GetStripeCustomerID(user, false)) + assert.Equal(t, "", GetStripeCustomerID(&User{StripeCustomer: "cus_legacy"}, true)) + assert.Equal(t, "cus_legacy", GetStripeCustomerID(&User{StripeCustomer: "cus_legacy"}, false)) + assert.Equal(t, "", GetStripeCustomerID(nil, false)) +} + +func TestRechargeStoresStripeCustomerByLivemode(t *testing.T) { + truncateTables(t) + + user := &User{ + Id: 601, + Username: "stripe_customer_user", + Status: common.UserStatusEnabled, + } + require.NoError(t, DB.Create(user).Error) + + insertStripeTopUpForCustomerTest(t, "stripe-test-customer", user.Id) + require.NoError(t, Recharge("stripe-test-customer", "cus_test_123", false, "127.0.0.1")) + + var stored User + require.NoError(t, DB.First(&stored, "id = ?", user.Id).Error) + assert.Equal(t, "cus_test_123", stored.StripeCustomer) + assert.Equal(t, "cus_test_123", stored.StripeCustomerTest) + assert.Empty(t, stored.StripeCustomerLive) + + insertStripeTopUpForCustomerTest(t, "stripe-live-customer", user.Id) + require.NoError(t, Recharge("stripe-live-customer", "cus_live_123", true, "127.0.0.1")) + + require.NoError(t, DB.First(&stored, "id = ?", user.Id).Error) + assert.Equal(t, "cus_test_123", stored.StripeCustomer) + assert.Equal(t, "cus_test_123", stored.StripeCustomerTest) + assert.Equal(t, "cus_live_123", stored.StripeCustomerLive) +} + +func TestCompleteStripeSubscriptionOrderStoresCustomerByLivemode(t *testing.T) { + truncateTables(t) + + user := &User{ + Id: 602, + Username: "stripe_subscription_user", + Status: common.UserStatusEnabled, + } + require.NoError(t, DB.Create(user).Error) + plan := insertSubscriptionPlanForPaymentGuardTest(t, 702) + insertSubscriptionOrderForPaymentGuardTest(t, "sub-stripe-customer", user.Id, plan.Id, PaymentProviderStripe) + + err := CompleteStripeSubscriptionOrder("sub-stripe-customer", `{"customer":"cus_live_sub"}`, "cus_live_sub", true) + require.NoError(t, err) + + var stored User + require.NoError(t, DB.First(&stored, "id = ?", user.Id).Error) + assert.Empty(t, stored.StripeCustomer) + assert.Empty(t, stored.StripeCustomerTest) + assert.Equal(t, "cus_live_sub", stored.StripeCustomerLive) +} + +func insertStripeTopUpForCustomerTest(t *testing.T, tradeNo string, userID int) { + t.Helper() + topUp := &TopUp{ + UserId: userID, + Amount: 1, + Money: 1, + TradeNo: tradeNo, + PaymentMethod: PaymentMethodStripe, + PaymentProvider: PaymentProviderStripe, + Status: common.TopUpStatusPending, + CreateTime: time.Now().Unix(), + } + require.NoError(t, topUp.Insert()) +} diff --git a/model/subscription.go b/model/subscription.go index da8fdae9410..a92741ce765 100644 --- a/model/subscription.go +++ b/model/subscription.go @@ -456,7 +456,7 @@ func CreateUserSubscriptionFromPlanTx(tx *gorm.DB, userId int, plan *Subscriptio return nil, errors.New("已达到该套餐购买上限") } } - nowUnix := GetDBTimestamp() + nowUnix := GetDBTimestampTx(tx) now := time.Unix(nowUnix, 0) endUnix, err := calcPlanEndTime(now, plan) if err != nil { @@ -509,6 +509,14 @@ func CreateUserSubscriptionFromPlanTx(tx *gorm.DB, userId int, plan *Subscriptio // expectedPaymentProvider guards against cross-gateway callback attacks (empty skips the check). // actualPaymentMethod updates the order's PaymentMethod to reflect the real payment type used (empty skips update). func CompleteSubscriptionOrder(tradeNo string, providerPayload string, expectedPaymentProvider string, actualPaymentMethod string) error { + return completeSubscriptionOrder(tradeNo, providerPayload, expectedPaymentProvider, actualPaymentMethod, "", false) +} + +func CompleteStripeSubscriptionOrder(tradeNo string, providerPayload string, customerId string, stripeLiveMode bool) error { + return completeSubscriptionOrder(tradeNo, providerPayload, PaymentProviderStripe, "", customerId, stripeLiveMode) +} + +func completeSubscriptionOrder(tradeNo string, providerPayload string, expectedPaymentProvider string, actualPaymentMethod string, stripeCustomerId string, stripeLiveMode bool) error { if tradeNo == "" { return errors.New("tradeNo is empty") } @@ -530,12 +538,15 @@ func CompleteSubscriptionOrder(tradeNo string, providerPayload string, expectedP return ErrPaymentMethodMismatch } if order.Status == common.TopUpStatusSuccess { + if err := updateStripeCustomerForUserTx(tx, order.UserId, stripeCustomerId, stripeLiveMode); err != nil { + return err + } return nil } if order.Status != common.TopUpStatusPending { return ErrSubscriptionOrderStatusInvalid } - plan, err := GetSubscriptionPlanById(order.PlanId) + plan, err := getSubscriptionPlanByIdTx(tx, order.PlanId) if err != nil { return err } @@ -558,6 +569,9 @@ func CompleteSubscriptionOrder(tradeNo string, providerPayload string, expectedP if actualPaymentMethod != "" && order.PaymentMethod != actualPaymentMethod { order.PaymentMethod = actualPaymentMethod } + if err := updateStripeCustomerForUserTx(tx, order.UserId, stripeCustomerId, stripeLiveMode); err != nil { + return err + } if err := tx.Save(&order).Error; err != nil { return err } diff --git a/model/topup.go b/model/topup.go index c071b77b543..4838e7fcf9f 100644 --- a/model/topup.go +++ b/model/topup.go @@ -104,7 +104,7 @@ func UpdatePendingTopUpStatus(tradeNo string, expectedPaymentProvider string, ta }) } -func Recharge(referenceId string, customerId string, callerIp string) (err error) { +func Recharge(referenceId string, customerId string, stripeLiveMode bool, callerIp string) (err error) { if referenceId == "" { return errors.New("未提供支付单号") } @@ -139,7 +139,9 @@ func Recharge(referenceId string, customerId string, callerIp string) (err error } quota = topUp.Money * common.QuotaPerUnit - err = tx.Model(&User{}).Where("id = ?", topUp.UserId).Updates(map[string]interface{}{"stripe_customer": customerId, "quota": gorm.Expr("quota + ?", quota)}).Error + updateFields := stripeCustomerUpdateFields(customerId, stripeLiveMode) + updateFields["quota"] = gorm.Expr("quota + ?", quota) + err = tx.Model(&User{}).Where("id = ?", topUp.UserId).Updates(updateFields).Error if err != nil { return err } diff --git a/model/user.go b/model/user.go index b632ef9afad..8c85126f4bf 100644 --- a/model/user.go +++ b/model/user.go @@ -2,7 +2,6 @@ package model import ( "database/sql" - "encoding/json" "errors" "fmt" "strconv" @@ -21,37 +20,76 @@ const UserNameMaxLength = 20 // User if you add sensitive fields, don't forget to clean them in setupLogin function. // Otherwise, the sensitive information will be saved on local storage in plain text! type User struct { - Id int `json:"id"` - Username string `json:"username" gorm:"unique;index" validate:"max=20"` - Password string `json:"password" gorm:"not null;" validate:"min=8,max=20"` - OriginalPassword string `json:"original_password" gorm:"-:all"` // this field is only for Password change verification, don't save it to database! - DisplayName string `json:"display_name" gorm:"index" validate:"max=20"` - Role int `json:"role" gorm:"type:int;default:1"` // admin, common - Status int `json:"status" gorm:"type:int;default:1"` // enabled, disabled - Email string `json:"email" gorm:"index" validate:"max=50"` - GitHubId string `json:"github_id" gorm:"column:github_id;index"` - DiscordId string `json:"discord_id" gorm:"column:discord_id;index"` - OidcId string `json:"oidc_id" gorm:"column:oidc_id;index"` - WeChatId string `json:"wechat_id" gorm:"column:wechat_id;index"` - TelegramId string `json:"telegram_id" gorm:"column:telegram_id;index"` - VerificationCode string `json:"verification_code" gorm:"-:all"` // this field is only for Email verification, don't save it to database! - AccessToken *string `json:"access_token" gorm:"type:char(32);column:access_token;uniqueIndex"` // this token is for system management - Quota int `json:"quota" gorm:"type:int;default:0"` - UsedQuota int `json:"used_quota" gorm:"type:int;default:0;column:used_quota"` // used quota - RequestCount int `json:"request_count" gorm:"type:int;default:0;"` // request number - Group string `json:"group" gorm:"type:varchar(64);default:'default'"` - AffCode string `json:"aff_code" gorm:"type:varchar(32);column:aff_code;uniqueIndex"` - AffCount int `json:"aff_count" gorm:"type:int;default:0;column:aff_count"` - AffQuota int `json:"aff_quota" gorm:"type:int;default:0;column:aff_quota"` // 邀请剩余额度 - AffHistoryQuota int `json:"aff_history_quota" gorm:"type:int;default:0;column:aff_history"` // 邀请历史额度 - InviterId int `json:"inviter_id" gorm:"type:int;column:inviter_id;index"` - DeletedAt gorm.DeletedAt `gorm:"index"` - LinuxDOId string `json:"linux_do_id" gorm:"column:linux_do_id;index"` - Setting string `json:"setting" gorm:"type:text;column:setting"` - Remark string `json:"remark,omitempty" gorm:"type:varchar(255)" validate:"max=255"` - StripeCustomer string `json:"stripe_customer" gorm:"type:varchar(64);column:stripe_customer;index"` - CreatedAt int64 `json:"created_at" gorm:"autoCreateTime;column:created_at"` - LastLoginAt int64 `json:"last_login_at" gorm:"default:0;column:last_login_at"` + Id int `json:"id"` + Username string `json:"username" gorm:"unique;index" validate:"max=20"` + Password string `json:"password" gorm:"not null;" validate:"min=8,max=20"` + OriginalPassword string `json:"original_password" gorm:"-:all"` // this field is only for Password change verification, don't save it to database! + DisplayName string `json:"display_name" gorm:"index" validate:"max=20"` + Role int `json:"role" gorm:"type:int;default:1"` // admin, common + Status int `json:"status" gorm:"type:int;default:1"` // enabled, disabled + Email string `json:"email" gorm:"index" validate:"max=50"` + GitHubId string `json:"github_id" gorm:"column:github_id;index"` + DiscordId string `json:"discord_id" gorm:"column:discord_id;index"` + OidcId string `json:"oidc_id" gorm:"column:oidc_id;index"` + WeChatId string `json:"wechat_id" gorm:"column:wechat_id;index"` + TelegramId string `json:"telegram_id" gorm:"column:telegram_id;index"` + VerificationCode string `json:"verification_code" gorm:"-:all"` // this field is only for Email verification, don't save it to database! + AccessToken *string `json:"access_token" gorm:"type:char(32);column:access_token;uniqueIndex"` // this token is for system management + Quota int `json:"quota" gorm:"type:int;default:0"` + UsedQuota int `json:"used_quota" gorm:"type:int;default:0;column:used_quota"` // used quota + RequestCount int `json:"request_count" gorm:"type:int;default:0;"` // request number + Group string `json:"group" gorm:"type:varchar(64);default:'default'"` + AffCode string `json:"aff_code" gorm:"type:varchar(32);column:aff_code;uniqueIndex"` + AffCount int `json:"aff_count" gorm:"type:int;default:0;column:aff_count"` + AffQuota int `json:"aff_quota" gorm:"type:int;default:0;column:aff_quota"` // 邀请剩余额度 + AffHistoryQuota int `json:"aff_history_quota" gorm:"type:int;default:0;column:aff_history"` // 邀请历史额度 + InviterId int `json:"inviter_id" gorm:"type:int;column:inviter_id;index"` + DeletedAt gorm.DeletedAt `gorm:"index"` + LinuxDOId string `json:"linux_do_id" gorm:"column:linux_do_id;index"` + Setting string `json:"setting" gorm:"type:text;column:setting"` + Remark string `json:"remark,omitempty" gorm:"type:varchar(255)" validate:"max=255"` + StripeCustomer string `json:"stripe_customer" gorm:"type:varchar(64);column:stripe_customer;index"` + StripeCustomerTest string `json:"stripe_customer_test" gorm:"type:varchar(64);column:stripe_customer_test;index"` + StripeCustomerLive string `json:"stripe_customer_live" gorm:"type:varchar(64);column:stripe_customer_live;index"` + CreatedAt int64 `json:"created_at" gorm:"autoCreateTime;column:created_at"` + LastLoginAt int64 `json:"last_login_at" gorm:"default:0;column:last_login_at"` +} + +func GetStripeCustomerID(user *User, liveMode bool) string { + if user == nil { + return "" + } + if liveMode { + return strings.TrimSpace(user.StripeCustomerLive) + } + if customerId := strings.TrimSpace(user.StripeCustomerTest); customerId != "" { + return customerId + } + return strings.TrimSpace(user.StripeCustomer) +} + +func stripeCustomerUpdateFields(customerId string, liveMode bool) map[string]interface{} { + customerId = strings.TrimSpace(customerId) + if customerId == "" { + return map[string]interface{}{} + } + if liveMode { + return map[string]interface{}{ + "stripe_customer_live": customerId, + } + } + return map[string]interface{}{ + "stripe_customer": customerId, + "stripe_customer_test": customerId, + } +} + +func updateStripeCustomerForUserTx(tx *gorm.DB, userId int, customerId string, liveMode bool) error { + updateFields := stripeCustomerUpdateFields(customerId, liveMode) + if len(updateFields) == 0 { + return nil + } + return tx.Model(&User{}).Where("id = ?", userId).Updates(updateFields).Error } func (user *User) ToBaseUser() *UserBase { @@ -81,7 +119,7 @@ func (user *User) SetAccessToken(token string) { func (user *User) GetSetting() dto.UserSetting { setting := dto.UserSetting{} if user.Setting != "" { - err := json.Unmarshal([]byte(user.Setting), &setting) + err := common.Unmarshal([]byte(user.Setting), &setting) if err != nil { common.SysLog("failed to unmarshal setting: " + err.Error()) } @@ -90,7 +128,7 @@ func (user *User) GetSetting() dto.UserSetting { } func (user *User) SetSetting(setting dto.UserSetting) { - settingBytes, err := json.Marshal(setting) + settingBytes, err := common.Marshal(setting) if err != nil { common.SysLog("failed to marshal setting: " + err.Error()) return @@ -151,7 +189,7 @@ func generateDefaultSidebarConfigForRole(userRole int) string { // 普通用户不包含admin区域 // 转换为JSON字符串 - configBytes, err := json.Marshal(defaultConfig) + configBytes, err := common.Marshal(defaultConfig) if err != nil { common.SysLog("生成默认边栏配置失败: " + err.Error()) return "" diff --git a/relay/channel/claude/relay-claude.go b/relay/channel/claude/relay-claude.go index e177e56dab1..be0e129f6fe 100644 --- a/relay/channel/claude/relay-claude.go +++ b/relay/channel/claude/relay-claude.go @@ -1,6 +1,7 @@ package claude import ( + "encoding/base64" "encoding/json" "fmt" "io" @@ -377,28 +378,14 @@ func RequestOpenAI2ClaudeMessage(c *gin.Context, textRequest dto.GeneralOpenAIRe }) } default: - source := mediaMessage.ToFileSource() - if source == nil { - continue - } - base64Data, mimeType, err := service.GetBase64Data(c, source, "formatting image for Claude") + claudeMediaMessage, err := convertMediaContentToClaudeMessage(c, mediaMessage) if err != nil { - return nil, fmt.Errorf("get file data failed: %s", err.Error()) - } - claudeMediaMessage := dto.ClaudeMediaMessage{ - Source: &dto.ClaudeMessageSource{ - Type: "base64", - }, + return nil, err } - if strings.HasPrefix(mimeType, "application/pdf") { - claudeMediaMessage.Type = "document" - } else { - claudeMediaMessage.Type = "image" + if claudeMediaMessage == nil { + continue } - - claudeMediaMessage.Source.MediaType = mimeType - claudeMediaMessage.Source.Data = base64Data - claudeMediaMessages = append(claudeMediaMessages, claudeMediaMessage) + claudeMediaMessages = append(claudeMediaMessages, *claudeMediaMessage) continue } } @@ -406,7 +393,7 @@ func RequestOpenAI2ClaudeMessage(c *gin.Context, textRequest dto.GeneralOpenAIRe if message.ToolCalls != nil { for _, toolCall := range message.ParseToolCalls() { inputObj := make(map[string]any) - if err := json.Unmarshal([]byte(toolCall.Function.Arguments), &inputObj); err != nil { + if err := common.Unmarshal([]byte(toolCall.Function.Arguments), &inputObj); err != nil { common.SysLog("tool call function arguments is not a map[string]any: " + fmt.Sprintf("%v", toolCall.Function.Arguments)) continue } @@ -434,6 +421,103 @@ func RequestOpenAI2ClaudeMessage(c *gin.Context, textRequest dto.GeneralOpenAIRe return &claudeRequest, nil } +func convertMediaContentToClaudeMessage(c *gin.Context, mediaMessage dto.MediaContent) (*dto.ClaudeMediaMessage, error) { + if mediaMessage.Type == dto.ContentTypeFile { + return convertOpenAIFileContentToClaudeMessage(c, mediaMessage) + } + + source := mediaMessage.ToFileSource() + if source == nil { + return nil, nil + } + base64Data, mimeType, err := service.GetBase64Data(c, source, "formatting media for Claude") + if err != nil { + return nil, fmt.Errorf("get file data failed: %s", err.Error()) + } + return buildClaudeBinaryMediaMessage(base64Data, mimeType), nil +} + +func convertOpenAIFileContentToClaudeMessage(c *gin.Context, mediaMessage dto.MediaContent) (*dto.ClaudeMediaMessage, error) { + file := mediaMessage.GetFile() + if file == nil || file.FileData == "" { + return nil, nil + } + + mimeType := messageFileMimeType(file) + if mimeType == "" || mimeType == "application/octet-stream" { + return nil, nil + } + + source := types.NewFileSourceFromData(file.FileData, mimeType) + base64Data, loadedMimeType, err := service.GetBase64Data(c, source, "formatting file for Claude") + if err != nil { + return nil, fmt.Errorf("get file data failed: %s", err.Error()) + } + if loadedMimeType != "" { + mimeType = loadedMimeType + } + + if strings.HasPrefix(mimeType, "text/") { + textBytes, err := base64.StdEncoding.DecodeString(base64Data) + if err != nil { + return nil, fmt.Errorf("decode text file failed: %s", err.Error()) + } + return &dto.ClaudeMediaMessage{ + Type: "text", + Text: common.GetPointer(string(textBytes)), + }, nil + } + + if strings.HasPrefix(mimeType, "application/pdf") || strings.HasPrefix(mimeType, "image/") { + return buildClaudeBinaryMediaMessage(base64Data, mimeType), nil + } + + return nil, nil +} + +func messageFileMimeType(file *dto.MessageFile) string { + if file == nil { + return "" + } + if mimeType := mimeTypeFromDataURI(file.FileData); mimeType != "" { + return mimeType + } + if dot := strings.LastIndex(file.FileName, "."); dot != -1 && dot+1 < len(file.FileName) { + return service.GetMimeTypeByExtension(file.FileName[dot+1:]) + } + return "" +} + +func mimeTypeFromDataURI(data string) string { + if !strings.HasPrefix(data, "data:") { + return "" + } + idx := strings.Index(data, ",") + if idx == -1 { + return "" + } + header := data[:idx] + if semi := strings.Index(header, ";"); semi != -1 && len("data:") < semi { + return header[len("data:"):semi] + } + return "" +} + +func buildClaudeBinaryMediaMessage(base64Data, mimeType string) *dto.ClaudeMediaMessage { + mediaType := "image" + if strings.HasPrefix(mimeType, "application/pdf") { + mediaType = "document" + } + return &dto.ClaudeMediaMessage{ + Type: mediaType, + Source: &dto.ClaudeMessageSource{ + Type: "base64", + MediaType: mimeType, + Data: base64Data, + }, + } +} + func StreamResponseClaude2OpenAI(claudeResponse *dto.ClaudeResponse) *dto.ChatCompletionsStreamResponse { var response dto.ChatCompletionsStreamResponse response.Object = "chat.completion.chunk" @@ -540,7 +624,7 @@ func ResponseClaude2OpenAI(claudeResponse *dto.ClaudeResponse) *dto.OpenAITextRe for _, message := range claudeResponse.Content { switch message.Type { case "tool_use": - args, _ := json.Marshal(message.Input) + args, _ := common.Marshal(message.Input) tools = append(tools, dto.ToolCallResponse{ ID: message.Id, Type: "function", // compatible with other OpenAI derivative applications @@ -919,7 +1003,7 @@ func HandleClaudeResponseData(c *gin.Context, info *relaycommon.RelayInfo, claud case types.RelayFormatOpenAI: openaiResponse := ResponseClaude2OpenAI(&claudeResponse) openaiResponse.Usage = buildOpenAIStyleUsageFromClaudeUsage(claudeInfo.Usage) - responseData, err = json.Marshal(openaiResponse) + responseData, err = common.Marshal(openaiResponse) if err != nil { return types.NewError(err, types.ErrorCodeBadResponseBody) } diff --git a/relay/helper/stream_scanner.go b/relay/helper/stream_scanner.go index a9bc5e16a72..07a32b7e3d8 100644 --- a/relay/helper/stream_scanner.go +++ b/relay/helper/stream_scanner.go @@ -24,6 +24,7 @@ import ( const ( InitialScannerBufferSize = 64 << 10 // 64KB (64*1024) DefaultMaxScannerBufferSize = 64 << 20 // 64MB (64*1024*1024) default SSE buffer size + DefaultStreamingTimeout = 300 * time.Second DefaultPingInterval = 10 * time.Second ) @@ -40,8 +41,9 @@ func StreamScannerHandler(c *gin.Context, resp *http.Response, info *relaycommon return } - // 无条件新建 StreamStatus - info.StreamStatus = relaycommon.NewStreamStatus() + if info.StreamStatus == nil { + info.StreamStatus = relaycommon.NewStreamStatus() + } // 确保响应体总是被关闭 defer func() { @@ -51,6 +53,9 @@ func StreamScannerHandler(c *gin.Context, resp *http.Response, info *relaycommon }() streamingTimeout := time.Duration(constant.StreamingTimeout) * time.Second + if streamingTimeout <= 0 { + streamingTimeout = DefaultStreamingTimeout + } var ( stopChan = make(chan bool, 3) // 增加缓冲区避免阻塞 diff --git a/service/channel_affinity_usage_cache_test.go b/service/channel_affinity_usage_cache_test.go index 64d3d715b54..8c44d5e4762 100644 --- a/service/channel_affinity_usage_cache_test.go +++ b/service/channel_affinity_usage_cache_test.go @@ -3,6 +3,7 @@ package service import ( "fmt" "net/http/httptest" + "sync/atomic" "testing" "time" @@ -12,6 +13,12 @@ import ( "github.com/stretchr/testify/require" ) +var channelAffinityUsageCacheTestSeq atomic.Int64 + +func uniqueChannelAffinityUsageCacheTestKey(prefix string) string { + return fmt.Sprintf("%s_%d_%d", prefix, time.Now().UnixNano(), channelAffinityUsageCacheTestSeq.Add(1)) +} + func buildChannelAffinityStatsContextForTest(ruleName, usingGroup, keyFP string) *gin.Context { rec := httptest.NewRecorder() ctx, _ := gin.CreateTestContext(rec) @@ -26,9 +33,9 @@ func buildChannelAffinityStatsContextForTest(ruleName, usingGroup, keyFP string) } func TestObserveChannelAffinityUsageCacheByRelayFormat_ClaudeMode(t *testing.T) { - ruleName := fmt.Sprintf("rule_%d", time.Now().UnixNano()) + ruleName := uniqueChannelAffinityUsageCacheTestKey("rule") usingGroup := "default" - keyFP := fmt.Sprintf("fp_%d", time.Now().UnixNano()) + keyFP := uniqueChannelAffinityUsageCacheTestKey("fp") ctx := buildChannelAffinityStatsContextForTest(ruleName, usingGroup, keyFP) usage := &dto.Usage{ @@ -53,9 +60,9 @@ func TestObserveChannelAffinityUsageCacheByRelayFormat_ClaudeMode(t *testing.T) } func TestObserveChannelAffinityUsageCacheByRelayFormat_MixedMode(t *testing.T) { - ruleName := fmt.Sprintf("rule_%d", time.Now().UnixNano()) + ruleName := uniqueChannelAffinityUsageCacheTestKey("rule") usingGroup := "default" - keyFP := fmt.Sprintf("fp_%d", time.Now().UnixNano()) + keyFP := uniqueChannelAffinityUsageCacheTestKey("fp") ctx := buildChannelAffinityStatsContextForTest(ruleName, usingGroup, keyFP) openAIUsage := &dto.Usage{ @@ -83,9 +90,9 @@ func TestObserveChannelAffinityUsageCacheByRelayFormat_MixedMode(t *testing.T) { } func TestObserveChannelAffinityUsageCacheByRelayFormat_UnsupportedModeKeepsEmpty(t *testing.T) { - ruleName := fmt.Sprintf("rule_%d", time.Now().UnixNano()) + ruleName := uniqueChannelAffinityUsageCacheTestKey("rule") usingGroup := "default" - keyFP := fmt.Sprintf("fp_%d", time.Now().UnixNano()) + keyFP := uniqueChannelAffinityUsageCacheTestKey("fp") ctx := buildChannelAffinityStatsContextForTest(ruleName, usingGroup, keyFP) usage := &dto.Usage{ diff --git a/setting/payment_stripe.go b/setting/payment_stripe.go index d97120c8523..7a05b3ae40f 100644 --- a/setting/payment_stripe.go +++ b/setting/payment_stripe.go @@ -6,3 +6,4 @@ var StripePriceId = "" var StripeUnitPrice = 8.0 var StripeMinTopUp = 1 var StripePromotionCodesEnabled = false +var StripeEnabled = true diff --git a/web/classic/src/components/settings/PaymentSetting.jsx b/web/classic/src/components/settings/PaymentSetting.jsx index 080c3e6e0ba..393432eca17 100644 --- a/web/classic/src/components/settings/PaymentSetting.jsx +++ b/web/classic/src/components/settings/PaymentSetting.jsx @@ -49,6 +49,7 @@ const PaymentSetting = () => { StripeUnitPrice: 8.0, StripeMinTopUp: 1, StripePromotionCodesEnabled: false, + StripeEnabled: true, WaffoPancakeEnabled: false, WaffoPancakeSandbox: false, diff --git a/web/classic/src/components/topup/SubscriptionPlansCard.jsx b/web/classic/src/components/topup/SubscriptionPlansCard.jsx index 9c50828372b..1d874cf3459 100644 --- a/web/classic/src/components/topup/SubscriptionPlansCard.jsx +++ b/web/classic/src/components/topup/SubscriptionPlansCard.jsx @@ -38,6 +38,11 @@ import { formatSubscriptionDuration, formatSubscriptionResetPeriod, } from '../../helpers/subscriptionFormat'; +import { + closePaymentWindow, + openPaymentWindow, + redirectPaymentWindow, +} from './paymentWindow'; const { Text } = Typography; @@ -118,23 +123,32 @@ const SubscriptionPlansCard = ({ showError(t('该套餐未配置 Stripe')); return; } + const stripePaymentWindow = openPaymentWindow('Stripe'); setPaying(true); try { const res = await API.post('/api/subscription/stripe/pay', { plan_id: selectedPlan.plan.id, }); if (res.data?.message === 'success') { - window.open(res.data.data?.pay_link, '_blank'); - showSuccess(t('已打开支付页面')); - closeBuy(); + const payLink = res.data.data?.pay_link || ''; + if (payLink) { + redirectPaymentWindow(stripePaymentWindow, payLink); + showSuccess(t('已打开支付页面')); + closeBuy(); + } else { + closePaymentWindow(stripePaymentWindow); + showError(t('支付请求失败')); + } } else { const errorMsg = typeof res.data?.data === 'string' ? res.data.data : res.data?.message || t('支付失败'); + closePaymentWindow(stripePaymentWindow); showError(errorMsg); } } catch (e) { + closePaymentWindow(stripePaymentWindow); showError(t('支付请求失败')); } finally { setPaying(false); diff --git a/web/classic/src/components/topup/index.jsx b/web/classic/src/components/topup/index.jsx index 1c23ca928c1..9454157cdba 100644 --- a/web/classic/src/components/topup/index.jsx +++ b/web/classic/src/components/topup/index.jsx @@ -39,6 +39,11 @@ import InvitationCard from './InvitationCard'; import TransferModal from './modals/TransferModal'; import PaymentConfirmModal from './modals/PaymentConfirmModal'; import TopupHistoryModal from './modals/TopupHistoryModal'; +import { + closePaymentWindow, + openPaymentWindow, + redirectPaymentWindow, +} from './paymentWindow'; const TopUp = () => { const { t } = useTranslation(); @@ -256,26 +261,34 @@ const TopUp = () => { return; } - if (payWay === 'stripe') { - // Stripe 支付处理 - if (amount === 0) { - await getStripeAmount(); - } - } else { - // 普通支付处理 - if (amount === 0) { - await getAmount(); - } - } + const isStripePayment = payWay === 'stripe'; + const selectedMinTopUp = getPaymentMinTopUp(payWay); - if (topUpCount < minTopUp) { - showError('充值数量不能小于' + minTopUp); + if (topUpCount < selectedMinTopUp) { + showError(t('充值数量不能小于') + selectedMinTopUp); return; } + + const stripePaymentWindow = isStripePayment + ? openPaymentWindow('Stripe') + : null; + setConfirmLoading(true); try { + if (isStripePayment) { + // Stripe 支付处理 + if (amount === 0) { + await getStripeAmount(); + } + } else { + // 普通支付处理 + if (amount === 0) { + await getAmount(); + } + } + let res; - if (payWay === 'stripe') { + if (isStripePayment) { // Stripe 支付请求 res = await API.post('/api/user/stripe/pay', { amount: parseInt(topUpCount), @@ -292,9 +305,15 @@ const TopUp = () => { if (res !== undefined) { const { message, data } = res.data; if (message === 'success') { - if (payWay === 'stripe') { + if (isStripePayment) { // Stripe 支付回调处理 - window.open(data.pay_link, '_blank'); + const payLink = data?.pay_link || ''; + if (payLink) { + redirectPaymentWindow(stripePaymentWindow, payLink); + } else { + closePaymentWindow(stripePaymentWindow); + showError(t('支付请求失败')); + } } else { // 普通支付表单提交 let params = data; @@ -322,12 +341,15 @@ const TopUp = () => { } else { const errorMsg = typeof data === 'string' ? data : message || t('支付失败'); + closePaymentWindow(stripePaymentWindow); showError(errorMsg); } } else { + closePaymentWindow(stripePaymentWindow); showError(res); } } catch (err) { + closePaymentWindow(stripePaymentWindow); showError(t('支付请求失败')); } finally { setOpen(false); @@ -647,7 +669,7 @@ const TopUp = () => { ? data.waffo_min_topup : enableWaffoPancakeTopUp ? data.waffo_pancake_min_topup - : 1; + : 1; setEnableOnlineTopUp(enableOnlineTopUp); setEnableStripeTopUp(enableStripeTopUp); setEnableCreemTopUp(enableCreemTopUp); diff --git a/web/classic/src/components/topup/paymentWindow.js b/web/classic/src/components/topup/paymentWindow.js new file mode 100644 index 00000000000..e4656882c02 --- /dev/null +++ b/web/classic/src/components/topup/paymentWindow.js @@ -0,0 +1,65 @@ +/* +Copyright (C) 2025 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 +*/ + +export const openPaymentWindow = (title = 'Payment') => { + if (typeof window === 'undefined') { + return null; + } + + const paymentWindow = window.open('', '_blank'); + if (!paymentWindow) { + return null; + } + + paymentWindow.document.title = title; + paymentWindow.document.body.style.margin = '0'; + paymentWindow.document.body.style.fontFamily = + 'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif'; + paymentWindow.document.body.innerHTML = ` +
+
+
Redirecting to payment...
+
Please keep this window open.
+
+
+ `; + paymentWindow.document.close(); + + return paymentWindow; +}; + +export const redirectPaymentWindow = (paymentWindow, url) => { + if (!url || typeof window === 'undefined') { + return false; + } + + if (paymentWindow && !paymentWindow.closed) { + paymentWindow.location.href = url; + return true; + } + + window.location.href = url; + return true; +}; + +export const closePaymentWindow = (paymentWindow) => { + if (paymentWindow && !paymentWindow.closed) { + paymentWindow.close(); + } +}; diff --git a/web/classic/src/i18n/locales/en.json b/web/classic/src/i18n/locales/en.json index 829a9e4b2a3..7d90526cdac 100644 --- a/web/classic/src/i18n/locales/en.json +++ b/web/classic/src/i18n/locales/en.json @@ -245,6 +245,8 @@ "SSRF防护详细说明": "SSRF protection prevents malicious users from using your server to access internal network resources. Configure whitelists for trusted domains/IPs and restrict allowed ports. Applies to file downloads, webhooks, and notifications.", "standard 已被移除,vip 用户看不到": "standard has been removed, vip users cannot see it", "store 字段用于授权 OpenAI 存储请求数据以评估和优化产品。默认关闭,开启后可能导致 Codex 无法正常使用": "The store field authorizes OpenAI to store request data for product evaluation and optimization. Disabled by default. Enabling may cause Codex to malfunction", + "启用 Stripe 充值": "Enable Stripe recharge", + "关闭后会保留密钥与价格配置,但用户无法使用 Stripe 支付": "When disabled, keys and price settings are kept, but users cannot pay with Stripe", "Stripe 设置": "Stripe Settings", "Stripe/Creem 商品ID(可选)": "Stripe/Creem Product ID (optional)", "Stripe/Creem 需在第三方平台创建商品并填入 ID": "Stripe/Creem products must be created on the third-party platform and the ID filled in", diff --git a/web/classic/src/i18n/locales/fr.json b/web/classic/src/i18n/locales/fr.json index e433dc8f72e..5e79ed17ac1 100644 --- a/web/classic/src/i18n/locales/fr.json +++ b/web/classic/src/i18n/locales/fr.json @@ -243,6 +243,8 @@ "SSRF防护详细说明": "La protection SSRF empêche les utilisateurs malveillants d'utiliser votre serveur pour accéder aux ressources du réseau interne. Configurez des listes blanches pour les domaines/IP de confiance et limitez les ports autorisés. S'applique aux téléchargements de fichiers, aux webhooks et aux notifications.", "standard 已被移除,vip 用户看不到": "standard has been removed, vip users cannot see it", "store 字段用于授权 OpenAI 存储请求数据以评估和优化产品。默认关闭,开启后可能导致 Codex 无法正常使用": "Le champ store autorise OpenAI à stocker les données de requête pour l'évaluation et l'optimisation du produit. Désactivé par défaut. L'activation peut causer un dysfonctionnement de Codex", + "启用 Stripe 充值": "Activer la recharge Stripe", + "关闭后会保留密钥与价格配置,但用户无法使用 Stripe 支付": "Une fois désactivé, les clés et la configuration des prix sont conservées, mais les utilisateurs ne peuvent pas payer avec Stripe", "Stripe 设置": "Paramètres Stripe", "Stripe/Creem 商品ID(可选)": "ID produit Stripe/Creem (optionnel)", "Stripe/Creem 需在第三方平台创建商品并填入 ID": "Les produits Stripe/Creem doivent être créés sur la plateforme tierce et l'ID doit être renseigné", diff --git a/web/classic/src/i18n/locales/ja.json b/web/classic/src/i18n/locales/ja.json index 5cfa0a2615f..2af4bee6f6e 100644 --- a/web/classic/src/i18n/locales/ja.json +++ b/web/classic/src/i18n/locales/ja.json @@ -237,6 +237,8 @@ "SSRF防护详细说明": "SSRF保護の詳細説明", "standard 已被移除,vip 用户看不到": "standard は削除され、vipユーザーには表示されません", "store 字段用于授权 OpenAI 存储请求数据以评估和优化产品。默认关闭,开启后可能导致 Codex 无法正常使用": "storeフィールドは、製品の評価と最適化のためにOpenAIがリクエストデータを保存することを許可します。デフォルトでは無効です。有効にすると、Codexが正常に利用できなくなる場合があります", + "启用 Stripe 充值": "Stripe チャージを有効化", + "关闭后会保留密钥与价格配置,但用户无法使用 Stripe 支付": "無効にするとキーと価格設定は保持されますが、ユーザーは Stripe で支払えません", "Stripe 设置": "Stripe 設定", "Stripe/Creem 商品ID(可选)": "Stripe/Creem 商品ID(任意)", "Stripe/Creem 需在第三方平台创建商品并填入 ID": "Stripe/Creem の商品は外部プラットフォームで作成し、ID を入力してください", diff --git a/web/classic/src/i18n/locales/ru.json b/web/classic/src/i18n/locales/ru.json index f4950bfeed8..bafe5b6b328 100644 --- a/web/classic/src/i18n/locales/ru.json +++ b/web/classic/src/i18n/locales/ru.json @@ -247,6 +247,8 @@ "SSRF防护详细说明": "Подробное описание защиты SSRF", "standard 已被移除,vip 用户看不到": "standard has been removed, vip users cannot see it", "store 字段用于授权 OpenAI 存储请求数据以评估和优化产品。默认关闭,开启后可能导致 Codex 无法正常使用": "Поле store используется для авторизации OpenAI хранить данные запросов для оценки и оптимизации продукта. По умолчанию отключено, после включения может привести к неработоспособности Codex", + "启用 Stripe 充值": "Включить пополнение Stripe", + "关闭后会保留密钥与价格配置,但用户无法使用 Stripe 支付": "После отключения ключи и настройки цен сохраняются, но пользователи не смогут платить через Stripe", "Stripe 设置": "Настройки Stripe", "Stripe/Creem 商品ID(可选)": "ID продукта Stripe/Creem (необязательно)", "Stripe/Creem 需在第三方平台创建商品并填入 ID": "Товары Stripe/Creem нужно создать на сторонней платформе и указать их ID", diff --git a/web/classic/src/i18n/locales/vi.json b/web/classic/src/i18n/locales/vi.json index 1d83bf6b738..16ab5cda525 100644 --- a/web/classic/src/i18n/locales/vi.json +++ b/web/classic/src/i18n/locales/vi.json @@ -238,6 +238,8 @@ "SSRF防护详细说明": "Bảo vệ SSRF ngăn chặn người dùng độc hại sử dụng máy chủ của bạn để truy cập tài nguyên mạng nội bộ. Cấu hình danh sách trắng cho các tên miền/IP đáng tin cậy và hạn chế các cổng được phép. Áp dụng cho tải xuống tệp, webhook và thông báo.", "standard 已被移除,vip 用户看不到": "standard has been removed, vip users cannot see it", "store 字段用于授权 OpenAI 存储请求数据以评估和优化产品。默认关闭,开启后可能导致 Codex 无法正常使用": "Trường store ủy quyền cho OpenAI lưu trữ dữ liệu yêu cầu để đánh giá và tối ưu hóa sản phẩm. Tắt theo mặc định. Bật có thể khiến Codex hoạt động không chính xác", + "启用 Stripe 充值": "Bật nạp tiền Stripe", + "关闭后会保留密钥与价格配置,但用户无法使用 Stripe 支付": "Khi tắt, khóa và cấu hình giá vẫn được giữ lại, nhưng người dùng không thể thanh toán bằng Stripe", "Stripe 设置": "Cài đặt Stripe", "Stripe/Creem 商品ID(可选)": "ID sản phẩm Stripe/Creem (tùy chọn)", "Stripe/Creem 需在第三方平台创建商品并填入 ID": "Sản phẩm Stripe/Creem phải được tạo trên nền tảng bên thứ ba và điền ID", diff --git a/web/classic/src/i18n/locales/zh-CN.json b/web/classic/src/i18n/locales/zh-CN.json index 2156b46d8ee..de1a39763cc 100644 --- a/web/classic/src/i18n/locales/zh-CN.json +++ b/web/classic/src/i18n/locales/zh-CN.json @@ -229,6 +229,8 @@ "SSRF防护详细说明": "SSRF防护可防止恶意用户利用您的服务器访问内网资源。您可以配置受信任域名/IP的白名单,并限制允许的端口。适用于文件下载、Webhook回调和通知功能。", "standard 已被移除,vip 用户看不到": "standard 已被移除,vip 用户看不到", "store 字段用于授权 OpenAI 存储请求数据以评估和优化产品。默认关闭,开启后可能导致 Codex 无法正常使用": "store 字段用于授权 OpenAI 存储请求数据以评估和优化产品。默认关闭,开启后可能导致 Codex 无法正常使用", + "启用 Stripe 充值": "启用 Stripe 充值", + "关闭后会保留密钥与价格配置,但用户无法使用 Stripe 支付": "关闭后会保留密钥与价格配置,但用户无法使用 Stripe 支付", "Stripe 设置": "Stripe 设置", "Stripe/Creem 商品ID(可选)": "Stripe/Creem 商品ID(可选)", "Stripe/Creem 需在第三方平台创建商品并填入 ID": "Stripe/Creem 需在第三方平台创建商品并填入 ID", diff --git a/web/classic/src/i18n/locales/zh-TW.json b/web/classic/src/i18n/locales/zh-TW.json index 98d8e892488..a0612ac8569 100644 --- a/web/classic/src/i18n/locales/zh-TW.json +++ b/web/classic/src/i18n/locales/zh-TW.json @@ -235,6 +235,8 @@ "SSRF防护详细说明": "SSRF防護可防止惡意使用者利用您的伺服器訪問內網資源。您可以設定受信任域名/IP的白名單,並限制允許的端口。適用於檔案下載、Webhook回調和通知功能。", "standard 已被移除,vip 用户看不到": "standard 已被移除,vip 使用者看不到", "store 字段用于授权 OpenAI 存储请求数据以评估和优化产品。默认关闭,开启后可能导致 Codex 无法正常使用": "store 字段用於授權 OpenAI 存儲請求數據以評估和優化產品。預設關閉,開啟後可能導致 Codex 無法正常使用", + "启用 Stripe 充值": "啟用 Stripe 儲值", + "关闭后会保留密钥与价格配置,但用户无法使用 Stripe 支付": "關閉後會保留密鑰與價格設定,但使用者無法使用 Stripe 支付", "Stripe 设置": "Stripe 設定", "Stripe/Creem 商品ID(可选)": "Stripe/Creem 商品ID(可選)", "Stripe/Creem 需在第三方平台创建商品并填入 ID": "Stripe/Creem 需在第三方平臺建立商品並填入 ID", diff --git a/web/classic/src/pages/Setting/Payment/SettingsPaymentGatewayStripe.jsx b/web/classic/src/pages/Setting/Payment/SettingsPaymentGatewayStripe.jsx index c8d3da2e402..caad3bd3892 100644 --- a/web/classic/src/pages/Setting/Payment/SettingsPaymentGatewayStripe.jsx +++ b/web/classic/src/pages/Setting/Payment/SettingsPaymentGatewayStripe.jsx @@ -39,6 +39,7 @@ export default function SettingsPaymentGateway(props) { StripeUnitPrice: 8.0, StripeMinTopUp: 1, StripePromotionCodesEnabled: false, + StripeEnabled: true, }); const [originInputs, setOriginInputs] = useState({}); const formApiRef = useRef(null); @@ -61,6 +62,10 @@ export default function SettingsPaymentGateway(props) { props.options.StripePromotionCodesEnabled !== undefined ? props.options.StripePromotionCodesEnabled : false, + StripeEnabled: + props.options.StripeEnabled !== undefined + ? props.options.StripeEnabled + : true, }; setInputs(currentInputs); setOriginInputs({ ...currentInputs }); @@ -112,6 +117,15 @@ export default function SettingsPaymentGateway(props) { value: inputs.StripeMinTopUp.toString(), }); } + if ( + originInputs['StripeEnabled'] !== inputs.StripeEnabled && + inputs.StripeEnabled !== undefined + ) { + options.push({ + key: 'StripeEnabled', + value: inputs.StripeEnabled ? 'true' : 'false', + }); + } if ( originInputs['StripePromotionCodesEnabled'] !== inputs.StripePromotionCodesEnabled && @@ -197,6 +211,21 @@ export default function SettingsPaymentGateway(props) { description='需要包含事件:checkout.session.completed 和 checkout.session.expired' style={{ marginBottom: 16 }} /> + + + + + = (props.purchaseLimit || 0) const handlePayStripe = async () => { + const stripePaymentWindow = openPaymentWindow('Stripe') setPaying(true) try { const res = await paySubscriptionStripe({ plan_id: plan.id }) if (res.message === 'success' && res.data?.pay_link) { - window.open(res.data.pay_link, '_blank') + redirectPaymentWindow(stripePaymentWindow, res.data.pay_link) toast.success(t('Payment page opened')) props.onOpenChange(false) } else { + closePaymentWindow(stripePaymentWindow) toast.error( res.message && res.message !== 'success' ? res.message @@ -87,6 +94,7 @@ export function SubscriptionPurchaseDialog(props: Props) { ) } } catch { + closePaymentWindow(stripePaymentWindow) toast.error(t('Payment request failed')) } finally { setPaying(false) diff --git a/web/default/src/features/system-settings/integrations/index.tsx b/web/default/src/features/system-settings/integrations/index.tsx index 33e19065d80..785fb44541f 100644 --- a/web/default/src/features/system-settings/integrations/index.tsx +++ b/web/default/src/features/system-settings/integrations/index.tsx @@ -43,6 +43,7 @@ const defaultIntegrationSettings: IntegrationSettingsType = { StripeUnitPrice: 8.0, StripeMinTopUp: 1, StripePromotionCodesEnabled: false, + StripeEnabled: true, CreemApiKey: '', CreemWebhookSecret: '', CreemTestMode: false, diff --git a/web/default/src/features/system-settings/integrations/payment-settings-section.tsx b/web/default/src/features/system-settings/integrations/payment-settings-section.tsx index 157e6356703..05668ff09a2 100644 --- a/web/default/src/features/system-settings/integrations/payment-settings-section.tsx +++ b/web/default/src/features/system-settings/integrations/payment-settings-section.tsx @@ -91,6 +91,7 @@ const paymentSchema = z.object({ StripeUnitPrice: z.coerce.number().min(0), StripeMinTopUp: z.coerce.number().min(0), StripePromotionCodesEnabled: z.boolean(), + StripeEnabled: z.boolean(), CreemApiKey: z.string(), CreemWebhookSecret: z.string(), CreemTestMode: z.boolean(), @@ -280,6 +281,7 @@ export function PaymentSettingsSection({ StripeMinTopUp: values.StripeMinTopUp as number, StripePromotionCodesEnabled: values.StripePromotionCodesEnabled as boolean, + StripeEnabled: values.StripeEnabled as boolean, } const initial = { @@ -290,6 +292,7 @@ export function PaymentSettingsSection({ StripeMinTopUp: initialRef.current.StripeMinTopUp, StripePromotionCodesEnabled: initialRef.current.StripePromotionCodesEnabled, + StripeEnabled: initialRef.current.StripeEnabled, } const updates: Array<{ key: string; value: string | number | boolean }> = [] @@ -333,6 +336,13 @@ export function PaymentSettingsSection({ }) } + if (sanitized.StripeEnabled !== initial.StripeEnabled) { + updates.push({ + key: 'StripeEnabled', + value: sanitized.StripeEnabled, + }) + } + if (updates.length === 0) { return } @@ -414,6 +424,7 @@ export function PaymentSettingsSection({ StripeUnitPrice: values.StripeUnitPrice, StripeMinTopUp: values.StripeMinTopUp, StripePromotionCodesEnabled: values.StripePromotionCodesEnabled, + StripeEnabled: values.StripeEnabled, } const initial = { @@ -435,6 +446,7 @@ export function PaymentSettingsSection({ StripeMinTopUp: initialRef.current.StripeMinTopUp, StripePromotionCodesEnabled: initialRef.current.StripePromotionCodesEnabled, + StripeEnabled: initialRef.current.StripeEnabled, } const updates: Array<{ key: string; value: string | number | boolean }> = [] @@ -532,6 +544,13 @@ export function PaymentSettingsSection({ }) } + if (sanitized.StripeEnabled !== initial.StripeEnabled) { + updates.push({ + key: 'StripeEnabled', + value: sanitized.StripeEnabled, + }) + } + for (const update of updates) { await updateOption.mutateAsync(update) } @@ -919,6 +938,31 @@ export function PaymentSettingsSection({

+ ( + +
+ + {t('Enable Stripe recharge')} + + + {t( + 'When disabled, Stripe keys and prices are kept but users cannot pay with Stripe' + )} + +
+ + + +
+ )} + /> +

{t('Webhook Configuration:')}

    diff --git a/web/default/src/features/system-settings/integrations/section-registry.tsx b/web/default/src/features/system-settings/integrations/section-registry.tsx index ff3f074139b..04276c4d55a 100644 --- a/web/default/src/features/system-settings/integrations/section-registry.tsx +++ b/web/default/src/features/system-settings/integrations/section-registry.tsx @@ -29,6 +29,7 @@ const INTEGRATIONS_SECTIONS = [ StripeUnitPrice: settings.StripeUnitPrice, StripeMinTopUp: settings.StripeMinTopUp, StripePromotionCodesEnabled: settings.StripePromotionCodesEnabled, + StripeEnabled: settings.StripeEnabled, CreemApiKey: settings.CreemApiKey, CreemWebhookSecret: settings.CreemWebhookSecret, CreemTestMode: settings.CreemTestMode, diff --git a/web/default/src/features/system-settings/types.ts b/web/default/src/features/system-settings/types.ts index 5c525475386..dff7a19764f 100644 --- a/web/default/src/features/system-settings/types.ts +++ b/web/default/src/features/system-settings/types.ts @@ -168,6 +168,7 @@ export type IntegrationSettings = { StripeUnitPrice: number StripeMinTopUp: number StripePromotionCodesEnabled: boolean + StripeEnabled: boolean CreemApiKey: string CreemWebhookSecret: string CreemTestMode: boolean diff --git a/web/default/src/features/wallet/hooks/use-payment.ts b/web/default/src/features/wallet/hooks/use-payment.ts index 41affb0cd72..97dd8445f5f 100644 --- a/web/default/src/features/wallet/hooks/use-payment.ts +++ b/web/default/src/features/wallet/hooks/use-payment.ts @@ -10,8 +10,11 @@ import { isApiSuccess, } from '../api' import { + closePaymentWindow, isStripePayment, isWaffoPancakePayment, + openPaymentWindow, + redirectPaymentWindow, submitPaymentForm, } from '../lib' @@ -60,11 +63,13 @@ export function usePayment() { // Process payment const processPayment = useCallback( async (topupAmount: number, paymentType: string) => { + let stripePaymentWindow: Window | null = null try { setProcessing(true) const isStripe = isStripePayment(paymentType) const amount = Math.floor(topupAmount) + stripePaymentWindow = isStripe ? openPaymentWindow('Stripe') : null const response = isStripe ? await requestStripePayment({ @@ -77,17 +82,23 @@ export function usePayment() { }) if (!isApiSuccess(response)) { + closePaymentWindow(stripePaymentWindow) toast.error(response.message || i18next.t('Payment request failed')) return false } // Handle Stripe payment if (isStripe && response.data?.pay_link) { - window.open(response.data.pay_link as string, '_blank') + redirectPaymentWindow( + stripePaymentWindow, + response.data.pay_link as string + ) toast.success(i18next.t('Redirecting to payment page...')) return true } + closePaymentWindow(stripePaymentWindow) + // Handle non-Stripe payment if (!isStripe && response.data) { const url = (response as unknown as { url?: string }).url @@ -100,6 +111,7 @@ export function usePayment() { return false } catch (_error) { + closePaymentWindow(stripePaymentWindow) toast.error(i18next.t('Payment request failed')) return false } finally { diff --git a/web/default/src/features/wallet/lib/payment.ts b/web/default/src/features/wallet/lib/payment.ts index 42ec92bd6aa..2f09dc218a5 100644 --- a/web/default/src/features/wallet/lib/payment.ts +++ b/web/default/src/features/wallet/lib/payment.ts @@ -50,6 +50,56 @@ export function submitPaymentForm( document.body.removeChild(form) } +export function openPaymentWindow(title = 'Payment'): Window | null { + if (typeof window === 'undefined') { + return null + } + + const paymentWindow = window.open('', '_blank') + if (!paymentWindow) { + return null + } + + paymentWindow.document.title = title + paymentWindow.document.body.style.margin = '0' + paymentWindow.document.body.style.fontFamily = + 'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif' + paymentWindow.document.body.innerHTML = ` +
    +
    +
    Redirecting to payment...
    +
    Please keep this window open.
    +
    +
    + ` + paymentWindow.document.close() + + return paymentWindow +} + +export function redirectPaymentWindow( + paymentWindow: Window | null, + url: string +): boolean { + if (!url || typeof window === 'undefined') { + return false + } + + if (paymentWindow && !paymentWindow.closed) { + paymentWindow.location.href = url + return true + } + + window.location.href = url + return true +} + +export function closePaymentWindow(paymentWindow: Window | null): void { + if (paymentWindow && !paymentWindow.closed) { + paymentWindow.close() + } +} + /** * Check if payment method is Stripe */ diff --git a/web/default/src/i18n/locales/en.json b/web/default/src/i18n/locales/en.json index eaf3e23121f..32dc0c5efbd 100644 --- a/web/default/src/i18n/locales/en.json +++ b/web/default/src/i18n/locales/en.json @@ -428,6 +428,7 @@ "Base amount. Actual deduction = base amount × system group rate.": "Base amount. Actual deduction = base amount × system group rate.", "Base Limits": "Base Limits", "Base multipliers applied when users select specific groups.": "Base multipliers applied when users select specific groups.", + "Base Price": "Base Price", "Base rate limit windows for this account.": "Base rate limit windows for this account.", "Base URL": "Base URL", "Base URL of your Uptime Kuma instance": "Base URL of your Uptime Kuma instance", @@ -485,7 +486,6 @@ "Broadcast a global banner to users. Markdown is supported.": "Broadcast a global banner to users. Markdown is supported.", "Broadcast short system notices on the dashboard": "Broadcast short system notices on the dashboard", "Browse and compare": "Browse and compare", - "Discover curated AI models, compare pricing and capabilities, and choose the right model for every scenario.": "Discover curated AI models, compare pricing and capabilities, and choose the right model for every scenario.", "Budget tokens = max tokens × ratio. Accepts a decimal between 0.002 and 1. Recommended to keep aligned with upstream billing.": "Budget tokens = max tokens × ratio. Accepts a decimal between 0.002 and 1. Recommended to keep aligned with upstream billing.", "Budget tokens = max tokens × ratio. Accepts a decimal between 0.1 and 1.": "Budget tokens = max tokens × ratio. Accepts a decimal between 0.1 and 1.", "Budget Tokens Ratio": "Budget Tokens Ratio", @@ -1069,6 +1069,7 @@ "Discount Rate:": "Discount Rate:", "Discount ratio for cache hits.": "Discount ratio for cache hits.", "Discouraged": "Discouraged", + "Discover curated AI models, compare pricing and capabilities, and choose the right model for every scenario.": "Discover curated AI models, compare pricing and capabilities, and choose the right model for every scenario.", "Discovering...": "Discovering...", "Disk cache cleared": "Disk cache cleared", "Disk Cache Settings": "Disk Cache Settings", @@ -1232,6 +1233,7 @@ "Enable SSL/TLS": "Enable SSL/TLS", "Enable SSRF Protection": "Enable SSRF Protection", "Enable streaming mode for the test request.": "Enable streaming mode for the test request.", + "Enable Stripe recharge": "Enable Stripe recharge", "Enable Telegram OAuth": "Enable Telegram OAuth", "Enable test mode for Creem payments": "Enable test mode for Creem payments", "Enable this key?": "Enable this key?", @@ -1815,9 +1817,9 @@ "Integrations": "Integrations", "Inter-group overrides": "Inter-group overrides", "Inter-group ratio overrides": "Inter-group ratio overrides", + "Interface Language": "Interface Language", "Internal Notes": "Internal Notes", "Internal notes (not shown to users)": "Internal notes (not shown to users)", - "Interface Language": "Interface Language", "Internal Server Error!": "Internal Server Error!", "Invalid chat link. Please contact the administrator.": "Invalid chat link. Please contact the administrator.", "Invalid chat link. Please contact your administrator.": "Invalid chat link. Please contact your administrator.", @@ -1894,8 +1896,8 @@ "Kling": "Kling", "Knowledge Base ID *": "Knowledge Base ID *", "Landing page with system overview.": "Landing page with system overview.", - "Language Preferences": "Language Preferences", "Language preference saved": "Language preference saved", + "Language Preferences": "Language Preferences", "Language preferences sync across your signed-in devices and affect API error messages.": "Language preferences sync across your signed-in devices and affect API error messages.", "Last check time": "Last check time", "Last detected addable models": "Last detected addable models", @@ -2660,7 +2662,6 @@ "Previous": "Previous", "Previous branch": "Previous branch", "Previous page": "Previous page", - "Base Price": "Base Price", "Price": "Price", "Price ($/1K calls)": "Price ($/1K calls)", "Price (local currency / USD)": "Price (local currency / USD)", @@ -3111,8 +3112,8 @@ "Select groups (leave empty to keep current)": "Select groups (leave empty to keep current)", "Select items...": "Select items...", "Select key format": "Select key format", - "Select Language": "Select Language", "Select language": "Select language", + "Select Language": "Select Language", "Select layout style": "Select layout style", "Select locations": "Select locations", "Select Model": "Select Model", @@ -3176,9 +3177,9 @@ "Set quota amount and limits": "Set quota amount and limits", "Set Request Header": "Set Request Header", "Set runtime request header: override entire value, or manipulate comma-separated tokens": "Set runtime request header: override entire value, or manipulate comma-separated tokens", - "Set the language used across the interface": "Set the language used across the interface", "Set Tag": "Set Tag", "Set tag for selected channels": "Set tag for selected channels", + "Set the language used across the interface": "Set the language used across the interface", "Set the user's role (cannot be Root)": "Set the user's role (cannot be Root)", "Setting saved": "Setting saved", "Setting up 2FA...": "Setting up 2FA...", @@ -3853,6 +3854,7 @@ "Well-Known URL must start with http:// or https://": "Well-Known URL must start with http:// or https://", "What would you like to know?": "What would you like to know?", "When conditions match, the final price is multiplied by X. Multiple matches multiply together; values < 1 act as discounts.": "When conditions match, the final price is multiplied by X. Multiple matches multiply together; values < 1 act as discounts.", + "When disabled, Stripe keys and prices are kept but users cannot pay with Stripe": "When disabled, Stripe keys and prices are kept but users cannot pay with Stripe", "When enabled, if channels in the current group fail, it will try channels in the next group in order.": "When enabled, if channels in the current group fail, it will try channels in the next group in order.", "When enabled, large request bodies are temporarily stored on disk instead of memory, significantly reducing memory usage. SSD recommended.": "When enabled, large request bodies are temporarily stored on disk instead of memory, significantly reducing memory usage. SSD recommended.", "When enabled, Midjourney callbacks are accepted (reveals server IP).": "When enabled, Midjourney callbacks are accepted (reveals server IP).", diff --git a/web/default/src/i18n/locales/fr.json b/web/default/src/i18n/locales/fr.json index f6b6657db93..b15ca8a65e9 100644 --- a/web/default/src/i18n/locales/fr.json +++ b/web/default/src/i18n/locales/fr.json @@ -428,6 +428,7 @@ "Base amount. Actual deduction = base amount × system group rate.": "Montant de base. Déduction réelle = montant de base × taux du groupe système.", "Base Limits": "Limites de base", "Base multipliers applied when users select specific groups.": "Multiplicateurs de base appliqués lorsque les utilisateurs sélectionnent des groupes spécifiques.", + "Base Price": "Prix de base", "Base rate limit windows for this account.": "Fenêtres de limitation de débit de base pour ce compte.", "Base URL": "URL de base", "Base URL of your Uptime Kuma instance": "URL de base de votre instance Uptime Kuma", @@ -485,7 +486,6 @@ "Broadcast a global banner to users. Markdown is supported.": "Diffuser une bannière globale aux utilisateurs. Le Markdown est pris en charge.", "Broadcast short system notices on the dashboard": "Diffuser de courtes notifications système sur le tableau de bord", "Browse and compare": "Parcourir et comparer", - "Discover curated AI models, compare pricing and capabilities, and choose the right model for every scenario.": "Découvrez une sélection de modèles IA, comparez les tarifs et les capacités, et choisissez le modèle adapté à chaque scénario.", "Budget tokens = max tokens × ratio. Accepts a decimal between 0.002 and 1. Recommended to keep aligned with upstream billing.": "Jetons budgétaires = jetons max × ratio. Accepte un nombre décimal entre 0,002 et 1. Il est recommandé de rester aligné avec la facturation en amont.", "Budget tokens = max tokens × ratio. Accepts a decimal between 0.1 and 1.": "Jetons budgétaires = jetons max × ratio. Accepte un nombre décimal entre 0,1 et 1.", "Budget Tokens Ratio": "Ratio de jetons budgétaires", @@ -1069,6 +1069,7 @@ "Discount Rate:": "Taux de réduction :", "Discount ratio for cache hits.": "Ratio de réduction pour les accès au cache.", "Discouraged": "Déconseillé", + "Discover curated AI models, compare pricing and capabilities, and choose the right model for every scenario.": "Découvrez une sélection de modèles IA, comparez les tarifs et les capacités, et choisissez le modèle adapté à chaque scénario.", "Discovering...": "Découverte en cours...", "Disk cache cleared": "Cache disque vidé", "Disk Cache Settings": "Paramètres du cache disque", @@ -1232,6 +1233,7 @@ "Enable SSL/TLS": "Activer SSL/TLS", "Enable SSRF Protection": "Activer la protection SSRF", "Enable streaming mode for the test request.": "Activer le mode streaming pour la requête de test.", + "Enable Stripe recharge": "Activer la recharge Stripe", "Enable Telegram OAuth": "Activer Telegram OAuth", "Enable test mode for Creem payments": "Activer le mode test pour les paiements Creem", "Enable this key?": "Activer cette clé ?", @@ -1815,9 +1817,9 @@ "Integrations": "Intégrations", "Inter-group overrides": "Dérogations inter-groupes", "Inter-group ratio overrides": "Dérogations de ratio inter-groupes", + "Interface Language": "Langue de l'interface", "Internal Notes": "Notes internes", "Internal notes (not shown to users)": "Notes internes (non visibles par les utilisateurs)", - "Interface Language": "Langue de l'interface", "Internal Server Error!": "Erreur interne du serveur !", "Invalid chat link. Please contact the administrator.": "Lien de chat invalide. Veuillez contacter l'administrateur.", "Invalid chat link. Please contact your administrator.": "Lien de chat invalide. Veuillez contacter votre administrateur.", @@ -1894,8 +1896,8 @@ "Kling": "Kling", "Knowledge Base ID *": "ID de la base de connaissances *", "Landing page with system overview.": "Page d'accueil avec aperçu du système.", - "Language Preferences": "Préférences de langue", "Language preference saved": "Préférence de langue enregistrée", + "Language Preferences": "Préférences de langue", "Language preferences sync across your signed-in devices and affect API error messages.": "Les préférences de langue se synchronisent sur vos appareils connectés et affectent les messages d'erreur de l'API.", "Last check time": "Dernière vérification", "Last detected addable models": "Derniers modèles ajoutables détectés", @@ -2660,7 +2662,6 @@ "Previous": "Précédent", "Previous branch": "Branche précédente", "Previous page": "Page précédente", - "Base Price": "Prix de base", "Price": "Prix", "Price ($/1K calls)": "Prix ($/1K appels)", "Price (local currency / USD)": "Prix (devise locale / USD)", @@ -3111,8 +3112,8 @@ "Select groups (leave empty to keep current)": "Sélectionner les groupes (laisser vide pour conserver les groupes actuels)", "Select items...": "Sélectionner des éléments...", "Select key format": "Sélectionner le format de clé", - "Select Language": "Sélectionner la langue", "Select language": "Sélectionner une langue", + "Select Language": "Sélectionner la langue", "Select layout style": "Sélectionner le style de mise en page", "Select locations": "Sélectionner des emplacements", "Select Model": "Sélectionner le modèle", @@ -3176,9 +3177,9 @@ "Set quota amount and limits": "Définir le quota et les limites", "Set Request Header": "Définir un en-tête de requête", "Set runtime request header: override entire value, or manipulate comma-separated tokens": "Définir l'en-tête de requête : remplacer la valeur ou manipuler les tokens séparés par des virgules", - "Set the language used across the interface": "Définir la langue utilisée dans l'interface", "Set Tag": "Définir un tag", "Set tag for selected channels": "Définir un tag pour les canaux sélectionnés", + "Set the language used across the interface": "Définir la langue utilisée dans l'interface", "Set the user's role (cannot be Root)": "Définir le rôle de l'utilisateur (ne peut pas être Root)", "Setting saved": "Paramètre sauvegardé", "Setting up 2FA...": "Configuration de la 2FA...", @@ -3853,6 +3854,7 @@ "Well-Known URL must start with http:// or https://": "L'URL bien connue doit commencer par http:// ou https://", "What would you like to know?": "Que voulez-vous savoir ?", "When conditions match, the final price is multiplied by X. Multiple matches multiply together; values < 1 act as discounts.": "Si les conditions sont remplies, le prix final est multiplié par X. Plusieurs correspondances se multiplient ; les valeurs < 1 agissent comme des remises.", + "When disabled, Stripe keys and prices are kept but users cannot pay with Stripe": "Une fois désactivé, les clés et la configuration des prix Stripe sont conservées, mais les utilisateurs ne peuvent pas payer avec Stripe", "When enabled, if channels in the current group fail, it will try channels in the next group in order.": "Lorsqu'elle est activée, si les canaux du groupe actuel échouent, le système essaiera les canaux du groupe suivant dans l'ordre.", "When enabled, large request bodies are temporarily stored on disk instead of memory, significantly reducing memory usage. SSD recommended.": "Lorsqu'activé, les corps de requête volumineux sont temporairement stockés sur disque, réduisant considérablement l'utilisation mémoire. SSD recommandé.", "When enabled, Midjourney callbacks are accepted (reveals server IP).": "Lorsque activé, les callbacks Midjourney sont acceptés (révèle l'IP du serveur).", diff --git a/web/default/src/i18n/locales/ja.json b/web/default/src/i18n/locales/ja.json index b62d4dabe71..4d31a79d576 100644 --- a/web/default/src/i18n/locales/ja.json +++ b/web/default/src/i18n/locales/ja.json @@ -428,6 +428,7 @@ "Base amount. Actual deduction = base amount × system group rate.": "基本金額。実際の控除 = 基本金額 × システムグループ倍率。", "Base Limits": "基本枠", "Base multipliers applied when users select specific groups.": "ユーザーが特定のグループを選択したときに適用される基本乗数。", + "Base Price": "基本価格", "Base rate limit windows for this account.": "このアカウント向けの基本レート制限ウィンドウ。", "Base URL": "ベースURL", "Base URL of your Uptime Kuma instance": "Uptime KumaインスタンスのベースURL", @@ -485,7 +486,6 @@ "Broadcast a global banner to users. Markdown is supported.": "ユーザーにグローバルバナーをブロードキャストします。Markdownがサポートされています。", "Broadcast short system notices on the dashboard": "ダッシュボードに短いシステム通知をブロードキャストします", "Browse and compare": "参照と比較", - "Discover curated AI models, compare pricing and capabilities, and choose the right model for every scenario.": "厳選された AI モデルを見つけ、価格と機能を比較し、あらゆるシナリオに適したモデルを選択できます。", "Budget tokens = max tokens × ratio. Accepts a decimal between 0.002 and 1. Recommended to keep aligned with upstream billing.": "予算トークン = 最大トークン × 比率。0.002から1までの小数を指定できます。アップストリームの請求と一致させることを推奨します。", "Budget tokens = max tokens × ratio. Accepts a decimal between 0.1 and 1.": "予算トークン = 最大トークン × 比率。0.1から1までの小数を指定できます。", "Budget Tokens Ratio": "予算トークン比率", @@ -1069,6 +1069,7 @@ "Discount Rate:": "割引率:", "Discount ratio for cache hits.": "キャッシュヒットに対する割引率。", "Discouraged": "非推奨", + "Discover curated AI models, compare pricing and capabilities, and choose the right model for every scenario.": "厳選された AI モデルを見つけ、価格と機能を比較し、あらゆるシナリオに適したモデルを選択できます。", "Discovering...": "検出中...", "Disk cache cleared": "ディスクキャッシュをクリアしました", "Disk Cache Settings": "ディスクキャッシュ設定", @@ -1232,6 +1233,7 @@ "Enable SSL/TLS": "SSL/TLSを有効にする", "Enable SSRF Protection": "SSRF保護を有効にする", "Enable streaming mode for the test request.": "テストリクエストのストリーミングモードを有効にします。", + "Enable Stripe recharge": "Stripeチャージを有効化", "Enable Telegram OAuth": "Telegram OAuthを有効にする", "Enable test mode for Creem payments": "Creem 決済のテストモードを有効にする", "Enable this key?": "このキーを有効にしますか?", @@ -1815,9 +1817,9 @@ "Integrations": "統合", "Inter-group overrides": "グループ間上書き", "Inter-group ratio overrides": "グループ間比率上書き", + "Interface Language": "インターフェース言語", "Internal Notes": "内部メモ", "Internal notes (not shown to users)": ":内部メモ(ユーザーには表示されません)", - "Interface Language": "インターフェース言語", "Internal Server Error!": "内部サーバーエラー!", "Invalid chat link. Please contact the administrator.": "無効なチャットリンクです。管理者に連絡してください。", "Invalid chat link. Please contact your administrator.": "無効なチャットリンクです。管理者に連絡してください。", @@ -1894,8 +1896,8 @@ "Kling": "Kling", "Knowledge Base ID *": "ナレッジベースID *", "Landing page with system overview.": "システム概要付きランディングページ。", - "Language Preferences": "言語設定", "Language preference saved": "言語設定を保存しました", + "Language Preferences": "言語設定", "Language preferences sync across your signed-in devices and affect API error messages.": "言語設定はログイン中のすべてのデバイスで同期され、API のエラーメッセージ言語にも反映されます。", "Last check time": "最終チェック時刻", "Last detected addable models": "最後に検出された追加可能モデル", @@ -2660,7 +2662,6 @@ "Previous": "前へ", "Previous branch": "前のブランチ", "Previous page": "前のページ", - "Base Price": "基本価格", "Price": "価格", "Price ($/1K calls)": "価格($/1K 回)", "Price (local currency / USD)": "価格 (現地通貨 / USD)", @@ -3111,8 +3112,8 @@ "Select groups (leave empty to keep current)": "グループを選択 (現在の設定を維持するには空のままにしてください)", "Select items...": "項目を選択...", "Select key format": "キーフォーマットを選択", - "Select Language": "言語を選択", "Select language": "言語を選択", + "Select Language": "言語を選択", "Select layout style": "レイアウトスタイルを選択", "Select locations": "ロケーションを選択", "Select Model": "モデルを選択", @@ -3176,9 +3177,9 @@ "Set quota amount and limits": "クォータ量と制限を設定", "Set Request Header": "リクエストヘッダーを設定", "Set runtime request header: override entire value, or manipulate comma-separated tokens": "ランタイムリクエストヘッダーを設定:値全体を上書き、またはカンマ区切りトークンを操作", - "Set the language used across the interface": "インターフェースで使用する言語を設定します", "Set Tag": "タグを設定", "Set tag for selected channels": "選択したチャネルにタグを設定", + "Set the language used across the interface": "インターフェースで使用する言語を設定します", "Set the user's role (cannot be Root)": "ユーザーのロールを設定します(Rootにはできません)", "Setting saved": "設定が保存されました", "Setting up 2FA...": "2FAを設定中...", @@ -3853,6 +3854,7 @@ "Well-Known URL must start with http:// or https://": "Well-Known URL は http:// または https:// で始まる必要があります", "What would you like to know?": "何を知りたいですか?", "When conditions match, the final price is multiplied by X. Multiple matches multiply together; values < 1 act as discounts.": "条件に一致したとき、最終価格に X を掛けます。複数一致は掛け合わさり、1 未満は割引として効きます。", + "When disabled, Stripe keys and prices are kept but users cannot pay with Stripe": "無効にするとStripeのキーと価格設定は保持されますが、ユーザーはStripeで支払えません", "When enabled, if channels in the current group fail, it will try channels in the next group in order.": "有効にすると、現在のグループのチャンネルが失敗した場合、次のグループのチャンネルを順番に試します。", "When enabled, large request bodies are temporarily stored on disk instead of memory, significantly reducing memory usage. SSD recommended.": "有効にすると、大きなリクエストボディはメモリではなくディスクに一時保存され、メモリ使用量が大幅に削減されます。SSD環境での使用を推奨します。", "When enabled, Midjourney callbacks are accepted (reveals server IP).": "有効にすると、Midjourney のコールバックを受け入れます (サーバーの IP を公開します)。", diff --git a/web/default/src/i18n/locales/ru.json b/web/default/src/i18n/locales/ru.json index 9aa4991a097..4e9b24ac2df 100644 --- a/web/default/src/i18n/locales/ru.json +++ b/web/default/src/i18n/locales/ru.json @@ -428,6 +428,7 @@ "Base amount. Actual deduction = base amount × system group rate.": "Базовая сумма. Фактический вычет = базовая сумма × коэффициент группы.", "Base Limits": "Базовые лимиты", "Base multipliers applied when users select specific groups.": "Базовые множители, применяемые, когда пользователи выбирают определенные группы.", + "Base Price": "Базовая цена", "Base rate limit windows for this account.": "Окна базовых лимитов для этого аккаунта.", "Base URL": "Адрес API", "Base URL of your Uptime Kuma instance": "Базовый URL вашего экземпляра Uptime Kuma", @@ -485,7 +486,6 @@ "Broadcast a global banner to users. Markdown is supported.": "Транслировать глобальный баннер пользователям. Поддерживается Markdown.", "Broadcast short system notices on the dashboard": "Транслировать короткие системные уведомления на панели управления", "Browse and compare": "Просмотр и сравнение", - "Discover curated AI models, compare pricing and capabilities, and choose the right model for every scenario.": "Откройте для себя подобранные AI-модели, сравнивайте цены и возможности и выбирайте подходящую модель для каждого сценария.", "Budget tokens = max tokens × ratio. Accepts a decimal between 0.002 and 1. Recommended to keep aligned with upstream billing.": "Бюджетные токены = макс. токены × соотношение. Принимает десятичное число от 0.002 до 1. Рекомендуется поддерживать в соответствии с биллингом вышестоящего провайдера.", "Budget tokens = max tokens × ratio. Accepts a decimal between 0.1 and 1.": "Бюджетные токены = макс. токены × соотношение. Принимает десятичное число от 0.1 до 1.", "Budget Tokens Ratio": "Соотношение бюджетных токенов", @@ -1069,6 +1069,7 @@ "Discount Rate:": "Ставка скидки:", "Discount ratio for cache hits.": "Коэффициент скидки для попаданий в кэш.", "Discouraged": "Не рекомендуется", + "Discover curated AI models, compare pricing and capabilities, and choose the right model for every scenario.": "Откройте для себя подобранные AI-модели, сравнивайте цены и возможности и выбирайте подходящую модель для каждого сценария.", "Discovering...": "Обнаружение...", "Disk cache cleared": "Дисковый кэш очищен", "Disk Cache Settings": "Настройки дискового кэша", @@ -1232,6 +1233,7 @@ "Enable SSL/TLS": "Включить SSL/TLS", "Enable SSRF Protection": "Включить защиту от SSRF", "Enable streaming mode for the test request.": "Включить потоковый режим для тестового запроса.", + "Enable Stripe recharge": "Включить пополнение Stripe", "Enable Telegram OAuth": "Включить Telegram OAuth", "Enable test mode for Creem payments": "Включить тестовый режим для платежей Creem", "Enable this key?": "Включить этот ключ?", @@ -1815,9 +1817,9 @@ "Integrations": "Интеграции", "Inter-group overrides": "Переопределения между группами", "Inter-group ratio overrides": "Переопределения соотношений между группами", + "Interface Language": "Язык интерфейса", "Internal Notes": "Внутренние заметки", "Internal notes (not shown to users)": "Внутренние заметки (не показываются пользователям)", - "Interface Language": "Язык интерфейса", "Internal Server Error!": "Внутренняя ошибка сервера!", "Invalid chat link. Please contact the administrator.": "Неверная ссылка на чат. Пожалуйста, обратитесь к администратору.", "Invalid chat link. Please contact your administrator.": "Недействительная ссылка чата. Обратитесь к администратору.", @@ -1894,8 +1896,8 @@ "Kling": "Kling", "Knowledge Base ID *": "ID базы знаний *", "Landing page with system overview.": "Главная страница с обзором системы.", - "Language Preferences": "Языковые настройки", "Language preference saved": "Языковая настройка сохранена", + "Language Preferences": "Языковые настройки", "Language preferences sync across your signed-in devices and affect API error messages.": "Языковые настройки синхронизируются на всех ваших устройствах после входа и влияют на язык сообщений об ошибках API.", "Last check time": "Время последней проверки", "Last detected addable models": "Последние обнаруженные модели для добавления", @@ -2660,7 +2662,6 @@ "Previous": "Предыдущий шаг", "Previous branch": "Предыдущая ветка", "Previous page": "Предыдущая страница", - "Base Price": "Базовая цена", "Price": "Цена", "Price ($/1K calls)": "Цена ($/1K вызовов)", "Price (local currency / USD)": "Цена (местная валюта / USD)", @@ -3111,8 +3112,8 @@ "Select groups (leave empty to keep current)": "Выбрать группы (оставьте пустым, чтобы сохранить текущие)", "Select items...": "Выберите элементы...", "Select key format": "Выберите формат ключа", - "Select Language": "Выбрать язык", "Select language": "Выберите язык", + "Select Language": "Выбрать язык", "Select layout style": "Выбрать стиль макета", "Select locations": "Выбрать локации", "Select Model": "Выбрать модель", @@ -3176,9 +3177,9 @@ "Set quota amount and limits": "Настройте квоту и лимиты", "Set Request Header": "Установить заголовок запроса", "Set runtime request header: override entire value, or manipulate comma-separated tokens": "Установить заголовок запроса: переопределить значение или управлять токенами через запятую", - "Set the language used across the interface": "Настроить язык интерфейса", "Set Tag": "Установить тег", "Set tag for selected channels": "Установить тег для выбранных каналов", + "Set the language used across the interface": "Настроить язык интерфейса", "Set the user's role (cannot be Root)": "Установить роль пользователя (не может быть Root)", "Setting saved": "Настройка сохранена", "Setting up 2FA...": "Настройка 2FA...", @@ -3853,6 +3854,7 @@ "Well-Known URL must start with http:// or https://": "Well-Known URL должен начинаться с http:// или https://", "What would you like to know?": "Что вы хотели бы узнать?", "When conditions match, the final price is multiplied by X. Multiple matches multiply together; values < 1 act as discounts.": "При совпадении условий итоговая цена умножается на X. Несколько совпадений умножаются вместе; значения < 1 действуют как скидки.", + "When disabled, Stripe keys and prices are kept but users cannot pay with Stripe": "После отключения ключи и настройки цен Stripe сохраняются, но пользователи не смогут платить через Stripe", "When enabled, if channels in the current group fail, it will try channels in the next group in order.": "Если включено, при сбое каналов в текущей группе система попробует каналы следующей группы по порядку.", "When enabled, large request bodies are temporarily stored on disk instead of memory, significantly reducing memory usage. SSD recommended.": "При включении большие тела запросов временно сохраняются на диске, что значительно снижает использование памяти. Рекомендуется SSD.", "When enabled, Midjourney callbacks are accepted (reveals server IP).": "При включении принимаются обратные вызовы Midjourney (раскрывает IP сервера).", diff --git a/web/default/src/i18n/locales/vi.json b/web/default/src/i18n/locales/vi.json index 194864dcab3..eef73aa52ef 100644 --- a/web/default/src/i18n/locales/vi.json +++ b/web/default/src/i18n/locales/vi.json @@ -428,6 +428,7 @@ "Base amount. Actual deduction = base amount × system group rate.": "Số tiền cơ sở. Số tiền trừ thực tế = số tiền cơ sở × tỷ lệ nhóm hệ thống.", "Base Limits": "Giới hạn cơ bản", "Base multipliers applied when users select specific groups.": "Hệ số nhân cơ bản được áp dụng khi người dùng chọn các nhóm cụ thể.", + "Base Price": "Giá cơ bản", "Base rate limit windows for this account.": "Cửa sổ giới hạn tốc độ cơ bản cho tài khoản này.", "Base URL": "URL cơ sở", "Base URL of your Uptime Kuma instance": "URL cơ sở của phiên bản Uptime Kuma của bạn", @@ -485,7 +486,6 @@ "Broadcast a global banner to users. Markdown is supported.": "Phát một biểu ngữ toàn cầu đến người dùng. Hỗ trợ Markdown.", "Broadcast short system notices on the dashboard": "Phát các thông báo hệ thống ngắn trên bảng điều khiển", "Browse and compare": "Duyệt và so sánh", - "Discover curated AI models, compare pricing and capabilities, and choose the right model for every scenario.": "Khám phá các mô hình AI được tuyển chọn, so sánh giá và khả năng, rồi chọn mô hình phù hợp cho từng kịch bản.", "Budget tokens = max tokens × ratio. Accepts a decimal between 0.002 and 1. Recommended to keep aligned with upstream billing.": "Số token ngân sách = số token tối đa × tỷ lệ. Chấp nhận một số thập phân từ 0.002 đến 1. Khuyến nghị nên giữ cho phù hợp với cách tính phí của nhà cung cấp.", "Budget tokens = max tokens × ratio. Accepts a decimal between 0.1 and 1.": "Số token ngân sách = số token tối đa × tỷ lệ. Chấp nhận một số thập phân từ 0.1 đến 1.", "Budget Tokens Ratio": "Tỷ lệ Mã thông báo Ngân sách", @@ -1069,6 +1069,7 @@ "Discount Rate:": "Tỷ lệ chiết khấu:", "Discount ratio for cache hits.": "Tỷ lệ chiết khấu cho lượt truy cập bộ nhớ đệm thành công.", "Discouraged": "Tuyệt vọng", + "Discover curated AI models, compare pricing and capabilities, and choose the right model for every scenario.": "Khám phá các mô hình AI được tuyển chọn, so sánh giá và khả năng, rồi chọn mô hình phù hợp cho từng kịch bản.", "Discovering...": "Đang khám phá...", "Disk cache cleared": "Đã xóa bộ nhớ đệm đĩa", "Disk Cache Settings": "Cài đặt bộ nhớ đệm đĩa", @@ -1232,6 +1233,7 @@ "Enable SSL/TLS": "Bật SSL/TLS", "Enable SSRF Protection": "Kích hoạt Bảo vệ SSRF", "Enable streaming mode for the test request.": "Bật chế độ streaming cho yêu cầu thử nghiệm.", + "Enable Stripe recharge": "Bật nạp tiền Stripe", "Enable Telegram OAuth": "Bật Telegram OAuth", "Enable test mode for Creem payments": "Bật chế độ thử nghiệm cho thanh toán Creem", "Enable this key?": "Kích hoạt khóa này?", @@ -1815,9 +1817,9 @@ "Integrations": "Tích hợp", "Inter-group overrides": "Ghi đè liên nhóm", "Inter-group ratio overrides": "Tỷ lệ liên nhóm ghi đè", + "Interface Language": "Ngôn ngữ giao diện", "Internal Notes": "Ghi chú nội bộ", "Internal notes (not shown to users)": "Ghi chú nội bộ (không hiển thị cho người dùng)", - "Interface Language": "Ngôn ngữ giao diện", "Internal Server Error!": "Lỗi máy chủ nội bộ!", "Invalid chat link. Please contact the administrator.": "Liên kết trò chuyện không hợp lệ. Vui lòng liên hệ quản trị viên.", "Invalid chat link. Please contact your administrator.": "Liên kết trò chuyện không hợp lệ. Vui lòng liên hệ với quản trị viên của bạn.", @@ -1894,8 +1896,8 @@ "Kling": "Kling", "Knowledge Base ID *": "Mã số Cơ sở kiến thức *", "Landing page with system overview.": "Trang chủ với tổng quan hệ thống.", - "Language Preferences": "Tùy chọn ngôn ngữ", "Language preference saved": "Đã lưu tùy chọn ngôn ngữ", + "Language Preferences": "Tùy chọn ngôn ngữ", "Language preferences sync across your signed-in devices and affect API error messages.": "Tùy chọn ngôn ngữ sẽ đồng bộ trên các thiết bị đã đăng nhập và ảnh hưởng đến ngôn ngữ thông báo lỗi API.", "Last check time": "Thời gian kiểm tra gần nhất", "Last detected addable models": "Mô hình có thể thêm được phát hiện gần nhất", @@ -2660,7 +2662,6 @@ "Previous": "Trước", "Previous branch": "Nhánh trước", "Previous page": "Trang trước", - "Base Price": "Giá cơ bản", "Price": "Giá", "Price ($/1K calls)": "Giá ($/1K lượt gọi)", "Price (local currency / USD)": "Giá (tiền tệ địa phương / USD)", @@ -3111,8 +3112,8 @@ "Select groups (leave empty to keep current)": "Chọn nhóm (để trống để giữ nguyên hiện tại)", "Select items...": "Chọn các mục...", "Select key format": "Chọn định dạng khóa", - "Select Language": "Chọn Ngôn ngữ", "Select language": "Chọn ngôn ngữ", + "Select Language": "Chọn Ngôn ngữ", "Select layout style": "Chọn kiểu bố cục", "Select locations": "Chọn vị trí", "Select Model": "Chọn mẫu", @@ -3176,9 +3177,9 @@ "Set quota amount and limits": "Thiết lập hạn mức và giới hạn", "Set Request Header": "Đặt header yêu cầu", "Set runtime request header: override entire value, or manipulate comma-separated tokens": "Đặt header yêu cầu runtime: ghi đè toàn bộ giá trị hoặc thao tác token phân cách bằng dấu phẩy", - "Set the language used across the interface": "Đặt ngôn ngữ sử dụng trong giao diện", "Set Tag": "Gán Thẻ", "Set tag for selected channels": "Đặt thẻ cho các kênh đã chọn", + "Set the language used across the interface": "Đặt ngôn ngữ sử dụng trong giao diện", "Set the user's role (cannot be Root)": "Đặt vai trò của người dùng (không được là Root)", "Setting saved": "Cài đặt đã được lưu", "Setting up 2FA...": "Đang thiết lập 2FA...", @@ -3853,6 +3854,7 @@ "Well-Known URL must start with http:// or https://": "URL Well-Known phải bắt đầu bằng http:// hoặc https://", "What would you like to know?": "Bạn muốn biết gì?", "When conditions match, the final price is multiplied by X. Multiple matches multiply together; values < 1 act as discounts.": "Khi thỏa điều kiện, giá cuối nhân với X. Nhiều điều kiện khớp nhân lại với nhau; giá trị < 1 hoạt động như giảm giá.", + "When disabled, Stripe keys and prices are kept but users cannot pay with Stripe": "Khi tắt, khóa và cấu hình giá Stripe vẫn được giữ lại, nhưng người dùng không thể thanh toán bằng Stripe", "When enabled, if channels in the current group fail, it will try channels in the next group in order.": "Khi được bật, nếu các kênh trong nhóm hiện tại thất bại, hệ thống sẽ thử các kênh của nhóm tiếp theo theo thứ tự.", "When enabled, large request bodies are temporarily stored on disk instead of memory, significantly reducing memory usage. SSD recommended.": "Khi bật, nội dung yêu cầu lớn sẽ được lưu tạm trên đĩa thay vì bộ nhớ, giảm đáng kể việc sử dụng bộ nhớ. Khuyến nghị dùng SSD.", "When enabled, Midjourney callbacks are accepted (reveals server IP).": "Khi được bật, các callback của Midjourney được chấp nhận (lộ IP máy chủ).", diff --git a/web/default/src/i18n/locales/zh.json b/web/default/src/i18n/locales/zh.json index 5755a489681..9675408ef9f 100644 --- a/web/default/src/i18n/locales/zh.json +++ b/web/default/src/i18n/locales/zh.json @@ -428,6 +428,7 @@ "Base amount. Actual deduction = base amount × system group rate.": "基础金额,实际扣费 = 基础金额 × 系统分组倍率。", "Base Limits": "基础额度", "Base multipliers applied when users select specific groups.": "当用户选择特定分组时应用的基础乘数。", + "Base Price": "基础价格", "Base rate limit windows for this account.": "当前账号的基础额度窗口。", "Base URL": "API 地址", "Base URL of your Uptime Kuma instance": "您的 Uptime Kuma 实例的基础 URL", @@ -485,7 +486,6 @@ "Broadcast a global banner to users. Markdown is supported.": "向用户广播全局横幅。支持 Markdown。", "Broadcast short system notices on the dashboard": "在仪表板上广播简短的系统通知", "Browse and compare": "浏览和比较", - "Discover curated AI models, compare pricing and capabilities, and choose the right model for every scenario.": "探索精选 AI 模型,清晰比较价格与能力,为不同场景选择合适的模型。", "Budget tokens = max tokens × ratio. Accepts a decimal between 0.002 and 1. Recommended to keep aligned with upstream billing.": "预算令牌 = 最大令牌数 × 比例。接受 0.002 到 1 之间的十进制数。建议与上游计费保持一致。", "Budget tokens = max tokens × ratio. Accepts a decimal between 0.1 and 1.": "预算令牌 = 最大令牌数 × 比例。接受 0.1 到 1 之间的十进制数。", "Budget Tokens Ratio": "预算令牌比例", @@ -1069,6 +1069,7 @@ "Discount Rate:": "折扣率:", "Discount ratio for cache hits.": "缓存命中时的折扣比例。", "Discouraged": "不推荐", + "Discover curated AI models, compare pricing and capabilities, and choose the right model for every scenario.": "探索精选 AI 模型,清晰比较价格与能力,为不同场景选择合适的模型。", "Discovering...": "发现中...", "Disk cache cleared": "磁盘缓存已清理", "Disk Cache Settings": "磁盘缓存设置", @@ -1232,6 +1233,7 @@ "Enable SSL/TLS": "启用 SSL/TLS", "Enable SSRF Protection": "启用 SSRF 保护", "Enable streaming mode for the test request.": "为测试请求启用流式模式。", + "Enable Stripe recharge": "启用 Stripe 充值", "Enable Telegram OAuth": "启用 Telegram OAuth", "Enable test mode for Creem payments": "启用 Creem 支付测试模式", "Enable this key?": "启用此密钥?", @@ -1815,9 +1817,9 @@ "Integrations": "集成", "Inter-group overrides": "分组间覆盖", "Inter-group ratio overrides": "分组间比例覆盖", + "Interface Language": "界面语言", "Internal Notes": "内部备注", "Internal notes (not shown to users)": "内部备注(不显示给用户)", - "Interface Language": "界面语言", "Internal Server Error!": "内部服务器错误!", "Invalid chat link. Please contact the administrator.": "无效的聊天链接。请联系管理员。", "Invalid chat link. Please contact your administrator.": "无效的聊天链接。请联系您的管理员。", @@ -1894,8 +1896,8 @@ "Kling": "Kling", "Knowledge Base ID *": "知识库 ID *", "Landing page with system overview.": "带有系统概览的登陆页面。", - "Language Preferences": "语言偏好", "Language preference saved": "语言偏好已保存", + "Language Preferences": "语言偏好", "Language preferences sync across your signed-in devices and affect API error messages.": "语言偏好会同步到您登录的所有设备,并影响 API 错误消息语言。", "Last check time": "上次检测时间", "Last detected addable models": "上次检测到可加入模型", @@ -2660,7 +2662,6 @@ "Previous": "上一步", "Previous branch": "上一分支", "Previous page": "上一页", - "Base Price": "基础价格", "Price": "价格", "Price ($/1K calls)": "价格($/1K 次)", "Price (local currency / USD)": "价格(本地货币/美元)", @@ -3111,8 +3112,8 @@ "Select groups (leave empty to keep current)": "选择分组(留空以保持当前设置)", "Select items...": "选择项目...", "Select key format": "请选择密钥格式", - "Select Language": "选择语言", "Select language": "选择语言", + "Select Language": "选择语言", "Select layout style": "选择布局样式", "Select locations": "选择位置", "Select Model": "选择模型", @@ -3176,9 +3177,9 @@ "Set quota amount and limits": "设置令牌可用额度和数量", "Set Request Header": "设置请求头", "Set runtime request header: override entire value, or manipulate comma-separated tokens": "设置运行期请求头:可直接覆盖整条值,也可对逗号分隔的 token 做处理", - "Set the language used across the interface": "设置界面显示语言", "Set Tag": "设置标签", "Set tag for selected channels": "为选定的渠道设置标签", + "Set the language used across the interface": "设置界面显示语言", "Set the user's role (cannot be Root)": "设置用户角色(不能是 Root)", "Setting saved": "设置已保存", "Setting up 2FA...": "正在设置 2FA...", @@ -3853,6 +3854,7 @@ "Well-Known URL must start with http:// or https://": "知名 URL 必须以 http:// 或 https:// 开头", "What would you like to know?": "您想了解什么?", "When conditions match, the final price is multiplied by X. Multiple matches multiply together; values < 1 act as discounts.": "条件满足时,最终价格乘以 X;多条命中的倍率会相乘;小于 1 的值为折扣。", + "When disabled, Stripe keys and prices are kept but users cannot pay with Stripe": "关闭后会保留 Stripe 密钥与价格配置,但用户无法使用 Stripe 支付", "When enabled, if channels in the current group fail, it will try channels in the next group in order.": "开启后,当前分组渠道失败时会按顺序尝试下一个分组的渠道。", "When enabled, large request bodies are temporarily stored on disk instead of memory, significantly reducing memory usage. SSD recommended.": "启用磁盘缓存后,大请求体将临时存储到磁盘而非内存,可显著降低内存占用。建议在 SSD 环境下使用。", "When enabled, Midjourney callbacks are accepted (reveals server IP).": "启用时,接受 Midjourney 回调 (会泄露服务器 IP)。",