--- /dev/null +++ b/controller/maltai_payment_ledger.go @@ -0,0 +1,60 @@ +package controller + +import ( + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "strings" + + "github.com/Calcium-Ion/go-epay/epay" + "github.com/QuantumNous/new-api/common" + "github.com/gin-gonic/gin" +) + +// The platform issues normal native orders with a private signer. Public EPay +// checkouts keep their merchant credentials and existing order numbers. +func maltaiLedgerKey() string { + common.OptionMapRWMutex.RLock() + defer common.OptionMapRWMutex.RUnlock() + key := common.OptionMap["MaltaiAlipayLedgerKey"] + if len(key) < 32 { + return "" + } + return key +} + +func maltaiLedgerForRequest(c *gin.Context) string { + proof := c.GetHeader("X-Maltai-Ledger") + if proof == "" { + return "" + } + key := maltaiLedgerKey() + mac := hmac.New(sha256.New, []byte(key)) + mac.Write([]byte(c.Request.Method + "\n" + c.Request.URL.Path)) + if key == "" || !hmac.Equal([]byte(proof), []byte(hex.EncodeToString(mac.Sum(nil)))) { + return "" + } + return key +} + +func maltaiEpayClient(ledger string) *epay.Client { + if ledger == "" { + return GetEpayClient() + } + client, err := epay.NewClient(&epay.Config{PartnerID: "maltai", Key: ledger}, "https://maltai-ledger.invalid") + if err != nil { + return nil + } + return client +} + +func maltaiEpayForTrade(trade string) *epay.Client { + if !strings.HasSuffix(trade, "_MLG") { + return GetEpayClient() + } + key := maltaiLedgerKey() + if key == "" || !isPaymentComplianceConfirmed() { + return nil + } + return maltaiEpayClient(key) +} --- a/controller/subscription_payment_epay.go +++ b/controller/subscription_payment_epay.go @@ -45,7 +45,12 @@ common.ApiErrorT(c, "Plan amount is too low") return } - if !operation_setting.ContainsPayMethod(req.PaymentMethod) { + ledger := maltaiLedgerForRequest(c) + if c.GetHeader("X-Maltai-Ledger") != "" && (ledger == "" || !isPaymentComplianceConfirmed()) { + common.ApiErrorT(c, "Payment information has not been configured by administrator") + return + } + if !(ledger != "" && req.PaymentMethod == "alipay") && !operation_setting.ContainsPayMethod(req.PaymentMethod) { common.ApiErrorT(c, "Payment method does not exist") return } @@ -78,7 +83,10 @@ tradeNo := fmt.Sprintf("%s%d", common.GetRandomString(6), time.Now().Unix()) tradeNo = fmt.Sprintf("SUBUSR%dNO%s", userId, tradeNo) - client := GetEpayClient() + if ledger != "" { + tradeNo += "_MLG" + } + client := maltaiEpayClient(ledger) if client == nil { common.ApiErrorT(c, "Payment information has not been configured by administrator") return @@ -141,7 +149,7 @@ return } - client := GetEpayClient() + client := maltaiEpayForTrade(params["out_trade_no"]) if client == nil { _, _ = c.Writer.Write([]byte("fail")) return @@ -196,7 +204,7 @@ return } - client := GetEpayClient() + client := maltaiEpayForTrade(params["out_trade_no"]) if client == nil { c.Redirect(http.StatusFound, paymentReturnPath("/wallet?pay=fail")) return --- a/controller/topup.go +++ b/controller/topup.go @@ -7,6 +7,7 @@ "net/http" "net/url" "strconv" + "strings" "sync" "time" @@ -28,6 +29,10 @@ // 获取支付方式 payMethods := operation_setting.PayMethods + ledger := maltaiLedgerForRequest(c) + if complianceConfirmed && ledger != "" && !operation_setting.ContainsPayMethod("alipay") { + payMethods = append(append([]map[string]string(nil), payMethods...), map[string]string{"type": "alipay", "name": "支付宝"}) + } if !complianceConfirmed { payMethods = []map[string]string{} } @@ -98,7 +103,8 @@ } data := gin.H{ - "enable_online_topup": isEpayTopUpEnabled(), + "enable_online_topup": isEpayTopUpEnabled() || (ledger != "" && complianceConfirmed), + "maltai_ledger_ready": ledger != "", "enable_stripe_topup": isStripeTopUpEnabled(), "enable_creem_topup": isCreemTopUpEnabled(), "enable_waffo_topup": enableWaffo, @@ -315,7 +321,12 @@ return } - if !operation_setting.ContainsPayMethod(req.PaymentMethod) { + ledger := maltaiLedgerForRequest(c) + if c.GetHeader("X-Maltai-Ledger") != "" && (ledger == "" || !isPaymentComplianceConfirmed()) { + paymentError(c, common.NewMessage("Payment information has not been configured by administrator")) + return + } + if !(ledger != "" && req.PaymentMethod == "alipay") && !operation_setting.ContainsPayMethod(req.PaymentMethod) { paymentError(c, common.NewMessage("Payment method does not exist")) return } @@ -325,7 +336,10 @@ notifyUrl, _ := url.Parse(callBackAddress + "/api/user/epay/notify") tradeNo := fmt.Sprintf("%s%d", common.GetRandomString(6), time.Now().Unix()) tradeNo = fmt.Sprintf("USR%dNO%s", id, tradeNo) - client := GetEpayClient() + if ledger != "" { + tradeNo += "_MLG" + } + client := maltaiEpayClient(ledger) if client == nil { paymentError(c, common.NewMessage("Payment information has not been configured by administrator")) return @@ -413,12 +427,6 @@ } func EpayNotify(c *gin.Context) { - if !isEpayWebhookEnabled() { - logger.LogWarn(c.Request.Context(), common.LogText("Epay webhook rejected reason=webhook_disabled path=%q client_ip=%s", c.Request.RequestURI, c.ClientIP())) - _, _ = c.Writer.Write([]byte("fail")) - return - } - var params map[string]string if c.Request.Method == "POST" { @@ -446,7 +454,13 @@ _, _ = c.Writer.Write([]byte("fail")) return } - client := GetEpayClient() + if !strings.HasSuffix(params["out_trade_no"], "_MLG") && !isEpayWebhookEnabled() { + logger.LogWarn(c.Request.Context(), common.LogText("Epay webhook rejected reason=webhook_disabled path=%q client_ip=%s", c.Request.RequestURI, c.ClientIP())) + _, _ = c.Writer.Write([]byte("fail")) + return + } + + client := maltaiEpayForTrade(params["out_trade_no"]) if client == nil { logger.LogError(c.Request.Context(), common.LogText("Epay client is not initialized path=%q client_ip=%s", c.Request.RequestURI, c.ClientIP())) _, err := c.Writer.Write([]byte("fail")) @@ -543,8 +557,9 @@ total int64 err error ) - if keyword != "" { - topups, total, err = model.SearchUserTopUps(userId, keyword, pageInfo) + walletOnly := c.Query("wallet_only") == "true" + if keyword != "" || walletOnly { + topups, total, err = model.SearchUserTopUps(userId, keyword, pageInfo, walletOnly) } else { topups, total, err = model.GetUserTopUps(userId, pageInfo) } --- a/model/option.go +++ b/model/option.go @@ -1,6 +1,7 @@ package model import ( + "errors" "maps" "strconv" "strings" @@ -286,6 +287,12 @@ } func UpdateOption(key string, value string) error { + if key == "MaltaiAlipayLedgerKey" { + if len(value) < 32 || len(value) > 256 { + return errors.New("invalid private payment ledger key length") + } + return UpdateOptionsBulk(map[string]string{key: value}) + } if IsRequestPolicyOption(key) { return UpdateRequestPolicyOptions(map[string]string{key: value}) } --- a/model/topup.go +++ b/model/topup.go @@ -367,7 +367,7 @@ const searchTopUpCountHardLimit = 10000 // SearchUserTopUps 按订单号搜索某用户的充值记录 -func SearchUserTopUps(userId int, keyword string, pageInfo *common.PageInfo) (topups []*TopUp, total int64, err error) { +func SearchUserTopUps(userId int, keyword string, pageInfo *common.PageInfo, walletOnly bool) (topups []*TopUp, total int64, err error) { tx := DB.Begin() if tx.Error != nil { return nil, 0, tx.Error @@ -379,6 +379,10 @@ }() query := tx.Model(&TopUp{}).Where("user_id = ? AND create_time >= ?", userId, topUpQueryCutoff()) + if walletOnly { + subscriptions := tx.Model(&SubscriptionOrder{}).Select("trade_no").Where("user_id = ? AND trade_no IS NOT NULL", userId) + query = query.Where("trade_no NOT IN (?) AND trade_no NOT LIKE ?", subscriptions, "SUBUSR%") + } if keyword != "" { pattern, perr := sanitizeLikePattern(keyword) if perr != nil {