Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions controller/payment_webhook_availability.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) != ""
}
Expand All @@ -18,7 +33,7 @@ func isStripeWebhookConfigured() bool {
}

func isStripeWebhookEnabled() bool {
return isStripeTopUpEnabled()
return isStripeWebhookConfigured()
}

func isCreemTopUpEnabled() bool {
Expand Down
33 changes: 31 additions & 2 deletions controller/payment_webhook_availability_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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) {
Expand Down
13 changes: 9 additions & 4 deletions controller/subscription_payment_stripe.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package controller
import (
"fmt"
"net/http"
"strings"
"time"

"github.com/QuantumNous/new-api/common"
Expand Down Expand Up @@ -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
}
Comment on lines +43 to +46

@coderabbitai coderabbitai Bot Apr 26, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

This turns the new top-up switch into a subscription kill switch.

SubscriptionRequestStripePay now refuses all Stripe subscription checkouts when setting.StripeEnabled is false. Based on the PR scope, that flag is the new Stripe recharge/top-up switch, so disabling one-time top-ups would also block selling subscriptions here.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@controller/subscription_payment_stripe.go` around lines 43 - 46, The current
guard in SubscriptionRequestStripePay uses setting.StripeEnabled to block all
Stripe flows; change it so the check only blocks one-time top-up/recharge flows.
Update the conditional in SubscriptionRequestStripePay to detect whether the
incoming request is a top-up (e.g., inspect the request payload/field that
distinguishes top-ups vs subscription checkouts) and only return an error when
setting.StripeEnabled is false AND the request is a top-up; allow normal
subscription checkout paths to proceed regardless of the top-up flag. Ensure you
reference setting.StripeEnabled and the request/property used to identify
top-ups (the field used in SubscriptionRequestStripePay) so reviewers can locate
the change.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Thanks for flagging this. This behavior is intentional.

In this project, StripeEnabled is intended to control whether users can initiate Stripe payments, not only one-time top-ups. Subscriptions and top-ups both create Stripe Checkout sessions, so if Stripe is disabled from the payment settings, subscription checkout should also be blocked. Otherwise, disabling Stripe recharge would still leave another Stripe payment entry point available.

Webhook processing remains independent from this switch, so existing or delayed Stripe events can still be handled even after Stripe payments are disabled.

The UI helper text also states that users cannot pay with Stripe when this option is disabled, so blocking subscription checkout is consistent with the intended behavior.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Only users with a collaborator, contributor, member, or owner role can interact with CodeRabbit.

if !isStripeAPISecretConfigured() {
common.ApiErrorMsg(c, "Stripe 未配置或密钥无效")
return
}
Expand Down Expand Up @@ -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": "拉起支付失败"})
Expand Down Expand Up @@ -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),
Expand Down
21 changes: 16 additions & 5 deletions controller/topup_stripe.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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": "拉起支付失败"})
Expand Down Expand Up @@ -270,16 +280,17 @@ 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) {
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
}

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
Expand Down Expand Up @@ -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 == "" {
Expand Down
19 changes: 15 additions & 4 deletions model/db_time.go
Original file line number Diff line number Diff line change
@@ -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()
Expand Down
3 changes: 3 additions & 0 deletions model/option.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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":
Expand Down
89 changes: 89 additions & 0 deletions model/stripe_customer_test.go
Original file line number Diff line number Diff line change
@@ -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())
}
18 changes: 16 additions & 2 deletions model/subscription.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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")
}
Expand All @@ -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
}
Expand All @@ -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
}
Expand Down
Loading