-
Notifications
You must be signed in to change notification settings - Fork 5k
feat: waffo pancake pay #4089
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
feat: waffo pancake pay #4089
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,228 @@ | ||
| package controller | ||
|
|
||
| import ( | ||
| "fmt" | ||
| "io" | ||
| "log" | ||
| "strings" | ||
| "time" | ||
|
|
||
| "github.com/QuantumNous/new-api/common" | ||
| "github.com/QuantumNous/new-api/model" | ||
| "github.com/QuantumNous/new-api/service" | ||
| "github.com/QuantumNous/new-api/setting" | ||
| "github.com/QuantumNous/new-api/setting/operation_setting" | ||
| "github.com/QuantumNous/new-api/setting/system_setting" | ||
| "github.com/gin-gonic/gin" | ||
| "github.com/shopspring/decimal" | ||
| "github.com/thanhpk/randstr" | ||
| ) | ||
|
|
||
| const PaymentMethodWaffoPancake = "waffo_pancake" | ||
|
|
||
| type WaffoPancakePayRequest struct { | ||
| Amount int64 `json:"amount"` | ||
| } | ||
|
|
||
| func getWaffoPancakePayMoney(amount int64, group string) float64 { | ||
| dAmount := decimal.NewFromInt(amount) | ||
| if operation_setting.GetQuotaDisplayType() == operation_setting.QuotaDisplayTypeTokens { | ||
| dAmount = dAmount.Div(decimal.NewFromFloat(common.QuotaPerUnit)) | ||
| } | ||
|
|
||
| topupGroupRatio := common.GetTopupGroupRatio(group) | ||
| if topupGroupRatio == 0 { | ||
| topupGroupRatio = 1 | ||
| } | ||
|
|
||
| discount := 1.0 | ||
| if ds, ok := operation_setting.GetPaymentSetting().AmountDiscount[int(amount)]; ok && ds > 0 { | ||
| discount = ds | ||
| } | ||
|
|
||
| payMoney := dAmount. | ||
| Mul(decimal.NewFromFloat(setting.WaffoPancakeUnitPrice)). | ||
| Mul(decimal.NewFromFloat(topupGroupRatio)). | ||
| Mul(decimal.NewFromFloat(discount)) | ||
|
|
||
| return payMoney.InexactFloat64() | ||
| } | ||
|
|
||
| func normalizeWaffoPancakeTopUpAmount(amount int64) int64 { | ||
| if operation_setting.GetQuotaDisplayType() != operation_setting.QuotaDisplayTypeTokens { | ||
| return amount | ||
| } | ||
|
|
||
| normalized := decimal.NewFromInt(amount). | ||
| Div(decimal.NewFromFloat(common.QuotaPerUnit)). | ||
| IntPart() | ||
| if normalized < 1 { | ||
| return 1 | ||
| } | ||
| return normalized | ||
| } | ||
|
|
||
| func waffoPancakeMoneyToMinorUnits(payMoney float64) int64 { | ||
| return decimal.NewFromFloat(payMoney). | ||
| Mul(decimal.NewFromInt(100)). | ||
| Round(0). | ||
| IntPart() | ||
| } | ||
|
|
||
| func getWaffoPancakeBuyerEmail(user *model.User) string { | ||
| if user != nil && strings.TrimSpace(user.Email) != "" { | ||
| return user.Email | ||
| } | ||
| if user != nil { | ||
| return fmt.Sprintf("%d@new-api.local", user.Id) | ||
| } | ||
| return "" | ||
| } | ||
|
|
||
| func getWaffoPancakeReturnURL() string { | ||
| if strings.TrimSpace(setting.WaffoPancakeReturnURL) != "" { | ||
| return setting.WaffoPancakeReturnURL | ||
| } | ||
| return strings.TrimRight(system_setting.ServerAddress, "/") + "/console/topup?show_history=true" | ||
| } | ||
|
|
||
| func RequestWaffoPancakePay(c *gin.Context) { | ||
| if !setting.WaffoPancakeEnabled { | ||
| c.JSON(200, gin.H{"message": "error", "data": "Waffo Pancake 支付未启用"}) | ||
| return | ||
| } | ||
| if strings.TrimSpace(setting.WaffoPancakeMerchantID) == "" || | ||
| strings.TrimSpace(setting.WaffoPancakePrivateKey) == "" || | ||
| strings.TrimSpace(setting.WaffoPancakeStoreID) == "" || | ||
| strings.TrimSpace(setting.WaffoPancakeProductID) == "" { | ||
| c.JSON(200, gin.H{"message": "error", "data": "Waffo Pancake 配置不完整"}) | ||
| return | ||
| } | ||
|
|
||
| var req WaffoPancakePayRequest | ||
| if err := c.ShouldBindJSON(&req); err != nil { | ||
| c.JSON(200, gin.H{"message": "error", "data": "参数错误"}) | ||
| return | ||
| } | ||
| if req.Amount < int64(setting.WaffoPancakeMinTopUp) { | ||
| c.JSON(200, gin.H{"message": "error", "data": fmt.Sprintf("充值数量不能小于 %d", setting.WaffoPancakeMinTopUp)}) | ||
| return | ||
| } | ||
|
|
||
| id := c.GetInt("id") | ||
| user, err := model.GetUserById(id, false) | ||
| if err != nil || user == nil { | ||
| c.JSON(200, gin.H{"message": "error", "data": "用户不存在"}) | ||
| return | ||
| } | ||
|
|
||
| group, err := model.GetUserGroup(id, true) | ||
| if err != nil { | ||
| c.JSON(200, gin.H{"message": "error", "data": "获取用户分组失败"}) | ||
| return | ||
| } | ||
|
|
||
| payMoney := getWaffoPancakePayMoney(req.Amount, group) | ||
| if payMoney < 0.01 { | ||
| c.JSON(200, gin.H{"message": "error", "data": "充值金额过低"}) | ||
| return | ||
| } | ||
|
|
||
| tradeNo := fmt.Sprintf("WAFFO_PANCAKE-%d-%d-%s", id, time.Now().UnixMilli(), randstr.String(6)) | ||
| topUp := &model.TopUp{ | ||
| UserId: id, | ||
| Amount: normalizeWaffoPancakeTopUpAmount(req.Amount), | ||
| Money: payMoney, | ||
| TradeNo: tradeNo, | ||
| PaymentMethod: PaymentMethodWaffoPancake, | ||
| CreateTime: time.Now().Unix(), | ||
| Status: common.TopUpStatusPending, | ||
| } | ||
| if err := topUp.Insert(); err != nil { | ||
| log.Printf("create Waffo Pancake topup failed: %v", err) | ||
| c.JSON(200, gin.H{"message": "error", "data": "创建订单失败"}) | ||
| return | ||
| } | ||
|
|
||
| expiresInSeconds := 45 * 60 | ||
| session, err := service.CreateWaffoPancakeCheckoutSession(c.Request.Context(), &service.WaffoPancakeCreateSessionParams{ | ||
| StoreID: setting.WaffoPancakeStoreID, | ||
| ProductID: setting.WaffoPancakeProductID, | ||
| ProductType: "onetime", | ||
| Currency: strings.ToUpper(strings.TrimSpace(setting.WaffoPancakeCurrency)), | ||
| PriceSnapshot: &service.WaffoPancakePriceSnapshot{ | ||
| Amount: waffoPancakeMoneyToMinorUnits(payMoney), | ||
| TaxIncluded: false, | ||
| TaxCategory: "saas", | ||
| }, | ||
| BuyerEmail: getWaffoPancakeBuyerEmail(user), | ||
| SuccessURL: getWaffoPancakeReturnURL(), | ||
| ExpiresInSeconds: &expiresInSeconds, | ||
| Metadata: map[string]string{ | ||
| "internalTradeNo": tradeNo, | ||
| "userId": fmt.Sprintf("%d", id), | ||
| "topupAmount": fmt.Sprintf("%d", req.Amount), | ||
| }, | ||
| }) | ||
| if err != nil { | ||
| log.Printf("create Waffo Pancake checkout session failed: %v", err) | ||
| topUp.Status = common.TopUpStatusFailed | ||
| _ = topUp.Update() | ||
| c.JSON(200, gin.H{"message": "error", "data": "拉起支付失败"}) | ||
| return | ||
| } | ||
|
|
||
| c.JSON(200, gin.H{ | ||
| "message": "success", | ||
| "data": gin.H{ | ||
| "checkout_url": session.CheckoutURL, | ||
| "session_id": session.SessionID, | ||
| "expires_at": session.ExpiresAt, | ||
| "order_id": tradeNo, | ||
| }, | ||
| }) | ||
| } | ||
|
|
||
| func WaffoPancakeWebhook(c *gin.Context) { | ||
| bodyBytes, err := io.ReadAll(c.Request.Body) | ||
| if err != nil { | ||
| log.Printf("read Waffo Pancake webhook body failed: %v", err) | ||
| c.String(400, "bad request") | ||
| return | ||
| } | ||
|
|
||
| signature := c.GetHeader("X-Waffo-Signature") | ||
| if signature == "" { | ||
| signature = c.GetHeader("X-Signature") | ||
| } | ||
|
|
||
| event, err := service.VerifyConfiguredWaffoPancakeWebhook(string(bodyBytes), signature) | ||
| if err != nil { | ||
| log.Printf("verify Waffo Pancake webhook failed: %v", err) | ||
| c.String(401, "invalid signature") | ||
| return | ||
| } | ||
|
|
||
| if event.NormalizedEventType() != "order.completed" { | ||
| c.String(200, "OK") | ||
| return | ||
| } | ||
|
|
||
| tradeNo := service.ExtractWaffoPancakeTradeNo(event) | ||
| if tradeNo == "" { | ||
| log.Printf("Waffo Pancake webhook missing internal trade no, event=%s", event.ID) | ||
| c.String(200, "OK") | ||
| return | ||
| } | ||
|
|
||
| LockOrder(tradeNo) | ||
| defer UnlockOrder(tradeNo) | ||
|
Comment on lines
+218
to
+219
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🧩 Analysis chain🏁 Script executed: #!/bin/bash
# Check how other webhook handlers in the codebase handle locking
rg -n -A5 "LockOrder|UnlockOrder" --type=goRepository: QuantumNous/new-api Length of output: 5240 🏁 Script executed: # View the complete LockOrder/UnlockOrder implementation
sed -n '278,310p' controller/topup.goRepository: QuantumNous/new-api Length of output: 678 🏁 Script executed: # Check if there's documentation or deployment configuration
fd -e md -e yaml -e yml -e json -e toml | head -20Repository: QuantumNous/new-api Length of output: 459 🏁 Script executed: # Search for deployment or distributed deployment references
rg -i "(distributed|deployment|multi.instance|cluster)" --type=go -l | head -10Repository: QuantumNous/new-api Length of output: 312 🏁 Script executed: # Check if Redis is configured and used elsewhere in the codebase
rg -i "redis" --type=go -l | head -10Repository: QuantumNous/new-api Length of output: 282 🏁 Script executed: # Check docker-compose.yml for multi-instance setup
cat docker-compose.ymlRepository: QuantumNous/new-api Length of output: 3338 🏁 Script executed: # Check README for deployment guidance
head -100 README.md | grep -i -A5 "deploy\|instance\|distributed"Repository: QuantumNous/new-api Length of output: 201 🏁 Script executed: # Search for any comments about single-instance assumptions in topup.go
rg -B5 -A5 "LockOrder|orderLocks" controller/topup.go | head -50Repository: QuantumNous/new-api Length of output: 953 In-process locking is insufficient for distributed deployments. The This pattern is pervasive across all webhook handlers (Epay, Stripe, Creem, Waffo, etc.). For multi-instance deployments, switch to database-level locking (e.g., 🤖 Prompt for AI Agents |
||
|
|
||
| if err := model.RechargeWaffoPancake(tradeNo); err != nil { | ||
| log.Printf("Waffo Pancake recharge failed: %v, trade_no=%s", err, tradeNo) | ||
| c.String(500, "retry") | ||
| return | ||
| } | ||
|
|
||
| c.String(200, "OK") | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Include webhook public-key readiness in
enableWaffoPancakegating.Current checks only validate merchant/private/store/product IDs. If webhook verify key is missing, users can pay but callback verification may fail and quota won’t be credited.
🔐 Suggested gating update
📝 Committable suggestion
🤖 Prompt for AI Agents