Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
62 changes: 49 additions & 13 deletions controller/topup.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,29 @@ import (

func GetTopUpInfo(c *gin.Context) {
complianceConfirmed := operation_setting.IsPaymentComplianceConfirmed()
minTopUp := effectiveGatewayMinTopUp(0)
stripeMinTopUp := effectiveGatewayMinTopUp(setting.StripeMinTopUp)
waffoMinTopUp := effectiveGatewayMinTopUp(setting.WaffoMinTopUp)
waffoPancakeMinTopUp := effectiveGatewayMinTopUp(setting.WaffoPancakeMinTopUp)

// 获取支付方式
payMethods := operation_setting.PayMethods
if !complianceConfirmed {
payMethods = []map[string]string{}
payMethods := make([]map[string]string, 0, len(operation_setting.PayMethods)+3)
if complianceConfirmed {
for _, method := range operation_setting.PayMethods {
copied := make(map[string]string, len(method)+1)
maps.Copy(copied, method)
floorMin := minTopUp
switch copied["type"] {
case "stripe":
floorMin = stripeMinTopUp
case model.PaymentMethodWaffoPancake:
floorMin = waffoPancakeMinTopUp
case model.PaymentMethodWaffo:
floorMin = waffoMinTopUp
}
copied["min_topup"] = resolvePayMethodMinTopUp(copied["min_topup"], floorMin)
payMethods = append(payMethods, copied)
}
}

// 如果启用了 Stripe 支付,添加到支付方法列表
Expand All @@ -49,7 +67,7 @@ func GetTopUpInfo(c *gin.Context) {
"name": "Stripe",
"type": "stripe",
"color": "#635BFF",
"min_topup": strconv.Itoa(setting.StripeMinTopUp),
"min_topup": strconv.Itoa(stripeMinTopUp),
}
payMethods = append(payMethods, stripeMethod)
}
Expand All @@ -71,7 +89,7 @@ func GetTopUpInfo(c *gin.Context) {
"name": "Waffo Pancake",
"type": model.PaymentMethodWaffoPancake,
"color": "#F97316",
"min_topup": strconv.Itoa(setting.WaffoPancakeMinTopUp),
"min_topup": strconv.Itoa(waffoPancakeMinTopUp),
})
}
}
Expand All @@ -92,7 +110,7 @@ func GetTopUpInfo(c *gin.Context) {
"name": "Waffo (Global Payment)",
"type": model.PaymentMethodWaffo,
"color": "#3B82F6",
"min_topup": strconv.Itoa(setting.WaffoMinTopUp),
"min_topup": strconv.Itoa(waffoMinTopUp),
}
payMethods = append(payMethods, waffoMethod)
}
Expand All @@ -115,10 +133,10 @@ func GetTopUpInfo(c *gin.Context) {
}(),
"creem_products": setting.CreemProducts,
"pay_methods": payMethods,
"min_topup": operation_setting.MinTopUp,
"stripe_min_topup": setting.StripeMinTopUp,
"waffo_min_topup": setting.WaffoMinTopUp,
"waffo_pancake_min_topup": setting.WaffoPancakeMinTopUp,
"min_topup": minTopUp,
"stripe_min_topup": stripeMinTopUp,
"waffo_min_topup": waffoMinTopUp,
"waffo_pancake_min_topup": waffoPancakeMinTopUp,
Comment on lines +138 to +139

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.

Out of scope for this fix: the frontend wallet has never converted TOKENS display amounts to quota units before calling payment endpoints, whereas backend getMinTopup(), getStripeMinTopup(), RequestWaffoPay, and RequestWaffoPancakePay already operate on quota units in TOKENS mode. Addressing that pre-existing frontend unit mismatch is a separate change.

"amount_options": operation_setting.GetPaymentSetting().AmountOptions,
"discount": operation_setting.GetPaymentSetting().AmountDiscount,
"topup_link": common.TopUpLink,
Expand Down Expand Up @@ -201,20 +219,38 @@ func getPayMoney(amount int64, group string) float64 {
return payMoney.InexactFloat64()
}

func getMinTopup() int64 {
minTopup := operation_setting.MinTopUp
func effectiveGatewayMinTopUp(gatewayMin int) int {
return max(gatewayMin, operation_setting.MinTopUp, 1)
}

func resolvePayMethodMinTopUp(raw string, floor int) string {
trimmed := strings.TrimSpace(raw)
if trimmed != "" {
if parsed, err := decimal.NewFromString(trimmed); err == nil && parsed.GreaterThanOrEqual(decimal.NewFromInt(int64(floor))) {
return trimmed
}
}
return strconv.Itoa(floor)
}

func effectiveGatewayMinTopUpAmount(gatewayMin int) int64 {
minTopup := effectiveGatewayMinTopUp(gatewayMin)
if operation_setting.GetQuotaDisplayType() == operation_setting.QuotaDisplayTypeTokens {
dMinTopup := decimal.NewFromInt(int64(minTopup))
dQuotaPerUnit := decimal.NewFromFloat(common.QuotaPerUnit)
quota, err := common.WalletQuotaFromDecimalStrict(dMinTopup.Mul(dQuotaPerUnit))
if err != nil {
return common.MaxWalletQuota
}
minTopup = quota
return int64(quota)
}
return int64(minTopup)
}

func getMinTopup() int64 {
return effectiveGatewayMinTopUpAmount(0)
}

func getTopUpQuota(amount int64) (int, error) {
quota := decimal.NewFromInt(amount)
if operation_setting.GetQuotaDisplayType() == operation_setting.QuotaDisplayTypeTokens {
Expand Down
6 changes: 1 addition & 5 deletions controller/topup_stripe.go
Original file line number Diff line number Diff line change
Expand Up @@ -443,9 +443,5 @@ func getStripePayMoney(amount float64, group string) float64 {
}

func getStripeMinTopup() int64 {
minTopup := setting.StripeMinTopUp
if operation_setting.GetQuotaDisplayType() == operation_setting.QuotaDisplayTypeTokens {
minTopup = minTopup * int(common.QuotaPerUnit)
}
return int64(minTopup)
return effectiveGatewayMinTopUpAmount(setting.StripeMinTopUp)
Comment thread
leoravyn marked this conversation as resolved.
Resolved
}
4 changes: 2 additions & 2 deletions controller/topup_waffo.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ func RequestWaffoAmount(c *gin.Context) {
return
}

waffoMinTopup := int64(setting.WaffoMinTopUp)
waffoMinTopup := effectiveGatewayMinTopUpAmount(setting.WaffoMinTopUp)
if req.Amount < waffoMinTopup {
paymentError(c, common.NewMessage("Top-up amount cannot be less than {{min}}", map[string]any{"min": waffoMinTopup}))
return
Expand Down Expand Up @@ -155,7 +155,7 @@ func RequestWaffoPay(c *gin.Context) {
paymentError(c, common.NewMessage("Invalid parameters"))
return
}
waffoMinTopup := int64(setting.WaffoMinTopUp)
waffoMinTopup := effectiveGatewayMinTopUpAmount(setting.WaffoMinTopUp)
if req.Amount < waffoMinTopup {
paymentError(c, common.NewMessage("Top-up amount cannot be less than {{min}}", map[string]any{"min": waffoMinTopup}))
return
Expand Down
10 changes: 6 additions & 4 deletions controller/topup_waffo_pancake.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,9 @@ func RequestWaffoPancakeAmount(c *gin.Context) {
return
}

if req.Amount < int64(setting.WaffoPancakeMinTopUp) {
paymentError(c, common.NewMessage("Top-up amount cannot be less than {{min}}", map[string]any{"min": setting.WaffoPancakeMinTopUp}))
minTopup := effectiveGatewayMinTopUpAmount(setting.WaffoPancakeMinTopUp)
if req.Amount < minTopup {
paymentError(c, common.NewMessage("Top-up amount cannot be less than {{min}}", map[string]any{"min": minTopup}))
return
}
id := c.GetInt("id")
Expand Down Expand Up @@ -350,8 +351,9 @@ func RequestWaffoPancakePay(c *gin.Context) {
paymentError(c, common.NewMessage("Invalid parameters"))
return
}
if req.Amount < int64(setting.WaffoPancakeMinTopUp) {
paymentError(c, common.NewMessage("Top-up amount cannot be less than {{min}}", map[string]any{"min": setting.WaffoPancakeMinTopUp}))
minTopup := effectiveGatewayMinTopUpAmount(setting.WaffoPancakeMinTopUp)
if req.Amount < minTopup {
paymentError(c, common.NewMessage("Top-up amount cannot be less than {{min}}", map[string]any{"min": minTopup}))
return
}
id := c.GetInt("id")
Expand Down
189 changes: 189 additions & 0 deletions controller/topup_waffo_pancake_test.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
package controller

import (
"encoding/json"
"maps"
"net/http"
"net/http/httptest"
"strings"
"testing"

"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/setting"
"github.com/QuantumNous/new-api/setting/operation_setting"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)

Expand Down Expand Up @@ -88,3 +94,186 @@ func TestGetWaffoPancakePayMoney(t *testing.T) {
})
}
}

func TestGlobalMinTopUpEnforcedOnWaffoPancakeAndTopUpInfo(t *testing.T) {
oldDisplayType := operation_setting.GetGeneralSetting().QuotaDisplayType
oldMinTopUp := operation_setting.MinTopUp
oldWaffoPancakeMin := setting.WaffoPancakeMinTopUp
oldWaffoMin := setting.WaffoMinTopUp
oldStripeMin := setting.StripeMinTopUp
oldWaffoPancakeMerchantID := setting.WaffoPancakeMerchantID
oldWaffoPancakePrivateKey := setting.WaffoPancakePrivateKey
oldWaffoPancakeProductID := setting.WaffoPancakeProductID
oldWaffoEnabled := setting.WaffoEnabled
oldWaffoSandbox := setting.WaffoSandbox
oldWaffoApiKey := setting.WaffoApiKey
oldWaffoPrivateKey := setting.WaffoPrivateKey
oldWaffoPublicCert := setting.WaffoPublicCert
oldStripeSecret := setting.StripeApiSecret
oldStripeWebhook := setting.StripeWebhookSecret
oldStripePrice := setting.StripePriceId
oldComplianceConfirmed := operation_setting.GetPaymentSetting().ComplianceConfirmed
oldComplianceVersion := operation_setting.GetPaymentSetting().ComplianceTermsVersion
oldPayMethods := operation_setting.PayMethods
oldGinMode := gin.Mode()

t.Cleanup(func() {
gin.SetMode(oldGinMode)
operation_setting.GetGeneralSetting().QuotaDisplayType = oldDisplayType
operation_setting.MinTopUp = oldMinTopUp
setting.WaffoPancakeMinTopUp = oldWaffoPancakeMin
setting.WaffoMinTopUp = oldWaffoMin
setting.StripeMinTopUp = oldStripeMin
setting.WaffoPancakeMerchantID = oldWaffoPancakeMerchantID
setting.WaffoPancakePrivateKey = oldWaffoPancakePrivateKey
setting.WaffoPancakeProductID = oldWaffoPancakeProductID
setting.WaffoEnabled = oldWaffoEnabled
setting.WaffoSandbox = oldWaffoSandbox
setting.WaffoApiKey = oldWaffoApiKey
setting.WaffoPrivateKey = oldWaffoPrivateKey
setting.WaffoPublicCert = oldWaffoPublicCert
setting.StripeApiSecret = oldStripeSecret
setting.StripeWebhookSecret = oldStripeWebhook
setting.StripePriceId = oldStripePrice
operation_setting.GetPaymentSetting().ComplianceConfirmed = oldComplianceConfirmed
operation_setting.GetPaymentSetting().ComplianceTermsVersion = oldComplianceVersion
operation_setting.PayMethods = oldPayMethods
})

operation_setting.GetGeneralSetting().QuotaDisplayType = operation_setting.QuotaDisplayTypeUSD
operation_setting.MinTopUp = 10
setting.WaffoPancakeMinTopUp = 1
setting.WaffoMinTopUp = 1
setting.StripeMinTopUp = 1
operation_setting.PayMethods = []map[string]string{
{"name": "Custom", "icon": "LuCreditCard", "type": "custom1", "min_topup": "50"},
{"name": "Custom Decimal", "icon": "LuCreditCard", "type": "custom2", "min_topup": "50.50"},
{"name": "Custom Below Floor", "icon": "LuCreditCard", "type": "custom3", "min_topup": "5.50"},
}

operation_setting.GetPaymentSetting().ComplianceConfirmed = true
operation_setting.GetPaymentSetting().ComplianceTermsVersion = operation_setting.CurrentComplianceTermsVersion
setting.WaffoPancakeMerchantID = "merchant_test"
setting.WaffoPancakePrivateKey = "private_test"
setting.WaffoPancakeProductID = "product_test"
setting.WaffoEnabled = true
setting.WaffoSandbox = false
setting.WaffoApiKey = "waffo_key"
setting.WaffoPrivateKey = "waffo_priv"
setting.WaffoPublicCert = "waffo_pub"
setting.StripeApiSecret = "sk_test_123"
setting.StripeWebhookSecret = "whsec_test_123"
setting.StripePriceId = "price_test_123"

gin.SetMode(gin.TestMode)

t.Run("RequestWaffoPancakeAmount rejects amount below MinTopUp", func(t *testing.T) {
recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)
ctx.Request = httptest.NewRequest(http.MethodPost, "/api/user/waffo-pancake/amount", strings.NewReader(`{"amount":5}`))
ctx.Request.Header.Set("Content-Type", "application/json")

RequestWaffoPancakeAmount(ctx)

require.Equal(t, http.StatusOK, recorder.Code)
require.JSONEq(t, `{"message":"error","data":"Top-up amount cannot be less than 10","message_key":"Top-up amount cannot be less than {{min}}","message_params":{"min":10}}`, recorder.Body.String())
})

t.Run("RequestWaffoPancakePay rejects amount below MinTopUp", func(t *testing.T) {
recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)
ctx.Request = httptest.NewRequest(http.MethodPost, "/api/user/waffo-pancake/pay", strings.NewReader(`{"amount":5}`))
ctx.Request.Header.Set("Content-Type", "application/json")

RequestWaffoPancakePay(ctx)

require.Equal(t, http.StatusOK, recorder.Code)
require.JSONEq(t, `{"message":"error","data":"Top-up amount cannot be less than 10","message_key":"Top-up amount cannot be less than {{min}}","message_params":{"min":10}}`, recorder.Body.String())
})

t.Run("RequestWaffoAmount and RequestWaffoPay reject amount below MinTopUp", func(t *testing.T) {
recAmount := httptest.NewRecorder()
ctxAmount, _ := gin.CreateTestContext(recAmount)
ctxAmount.Request = httptest.NewRequest(http.MethodPost, "/api/user/waffo/amount", strings.NewReader(`{"amount":5}`))
ctxAmount.Request.Header.Set("Content-Type", "application/json")
RequestWaffoAmount(ctxAmount)
require.JSONEq(t, `{"message":"error","data":"Top-up amount cannot be less than 10","message_key":"Top-up amount cannot be less than {{min}}","message_params":{"min":10}}`, recAmount.Body.String())

recPay := httptest.NewRecorder()
ctxPay, _ := gin.CreateTestContext(recPay)
ctxPay.Request = httptest.NewRequest(http.MethodPost, "/api/user/waffo/pay", strings.NewReader(`{"amount":5}`))
ctxPay.Request.Header.Set("Content-Type", "application/json")
RequestWaffoPay(ctxPay)
require.JSONEq(t, `{"message":"error","data":"Top-up amount cannot be less than 10","message_key":"Top-up amount cannot be less than {{min}}","message_params":{"min":10}}`, recPay.Body.String())
})

t.Run("RequestStripeAmount rejects amount below MinTopUp", func(t *testing.T) {
recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)
ctx.Request = httptest.NewRequest(http.MethodPost, "/api/user/stripe/amount", strings.NewReader(`{"amount":5}`))
ctx.Request.Header.Set("Content-Type", "application/json")
RequestStripeAmount(ctx)
require.JSONEq(t, `{"message":"error","data":"Top-up amount cannot be less than 10","message_key":"Top-up amount cannot be less than {{min}}","message_params":{"min":10}}`, recorder.Body.String())
})

t.Run("GetTopUpInfo reports effective minimum floor of 10 across gateways and pay_methods", func(t *testing.T) {
recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)
ctx.Request = httptest.NewRequest(http.MethodGet, "/api/user/topup/info", nil)

GetTopUpInfo(ctx)

require.Equal(t, http.StatusOK, recorder.Code)
var resp struct {
Success bool `json:"success"`
Data struct {
MinTopUp int `json:"min_topup"`
StripeMinTopUp int `json:"stripe_min_topup"`
WaffoMinTopUp int `json:"waffo_min_topup"`
WaffoPancakeMinTopUp int `json:"waffo_pancake_min_topup"`
PayMethods []map[string]string `json:"pay_methods"`
} `json:"data"`
}
require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &resp))
require.True(t, resp.Success)
require.Equal(t, 10, resp.Data.MinTopUp)
require.Equal(t, 10, resp.Data.StripeMinTopUp)
require.Equal(t, 10, resp.Data.WaffoMinTopUp)
require.Equal(t, 10, resp.Data.WaffoPancakeMinTopUp)

methodsByType := make(map[string]map[string]string, len(resp.Data.PayMethods))
for _, m := range resp.Data.PayMethods {
methodsByType[m["type"]] = m
}
require.Equal(t, "10", methodsByType[model.PaymentMethodWaffoPancake]["min_topup"])
require.Equal(t, "10", methodsByType[model.PaymentMethodWaffo]["min_topup"])
require.Equal(t, "10", methodsByType["stripe"]["min_topup"])
require.Equal(t, "50", methodsByType["custom1"]["min_topup"])
require.Equal(t, "50.50", methodsByType["custom2"]["min_topup"])
require.Equal(t, "10", methodsByType["custom3"]["min_topup"])

// Verify GetTopUpInfo does not mutate global operation_setting.PayMethods
require.Len(t, operation_setting.PayMethods, 3)
require.Equal(t, "5.50", operation_setting.PayMethods[2]["min_topup"])
})

t.Run("Tokens display mode scales effective minimum floor by QuotaPerUnit", func(t *testing.T) {
operation_setting.GetGeneralSetting().QuotaDisplayType = operation_setting.QuotaDisplayTypeTokens
t.Cleanup(func() {
operation_setting.GetGeneralSetting().QuotaDisplayType = operation_setting.QuotaDisplayTypeUSD
})

expectedMinTokens := int64(10 * common.QuotaPerUnit)
require.Equal(t, expectedMinTokens, effectiveGatewayMinTopUpAmount(setting.WaffoPancakeMinTopUp))

recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)
ctx.Request = httptest.NewRequest(http.MethodPost, "/api/user/waffo-pancake/amount", strings.NewReader(`{"amount":500000}`))
ctx.Request.Header.Set("Content-Type", "application/json")

RequestWaffoPancakeAmount(ctx)

require.Equal(t, http.StatusOK, recorder.Code)
require.JSONEq(t, `{"message":"error","data":"Top-up amount cannot be less than 5000000","message_key":"Top-up amount cannot be less than {{min}}","message_params":{"min":5000000}}`, recorder.Body.String())
})
}