topup.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. package controller
  2. import (
  3. "fmt"
  4. "log"
  5. "net/url"
  6. "strconv"
  7. "sync"
  8. "time"
  9. "github.com/QuantumNous/new-api/common"
  10. "github.com/QuantumNous/new-api/logger"
  11. "github.com/QuantumNous/new-api/model"
  12. "github.com/QuantumNous/new-api/service"
  13. "github.com/QuantumNous/new-api/setting"
  14. "github.com/QuantumNous/new-api/setting/operation_setting"
  15. "github.com/QuantumNous/new-api/setting/system_setting"
  16. "github.com/Calcium-Ion/go-epay/epay"
  17. "github.com/gin-gonic/gin"
  18. "github.com/samber/lo"
  19. "github.com/shopspring/decimal"
  20. )
  21. func GetTopUpInfo(c *gin.Context) {
  22. // 获取支付方式
  23. payMethods := operation_setting.PayMethods
  24. // 如果启用了 Stripe 支付,添加到支付方法列表
  25. if setting.StripeApiSecret != "" && setting.StripeWebhookSecret != "" && setting.StripePriceId != "" {
  26. // 检查是否已经包含 Stripe
  27. hasStripe := false
  28. for _, method := range payMethods {
  29. if method["type"] == "stripe" {
  30. hasStripe = true
  31. break
  32. }
  33. }
  34. if !hasStripe {
  35. stripeMethod := map[string]string{
  36. "name": "Stripe",
  37. "type": "stripe",
  38. "color": "rgba(var(--semi-purple-5), 1)",
  39. "min_topup": strconv.Itoa(setting.StripeMinTopUp),
  40. }
  41. payMethods = append(payMethods, stripeMethod)
  42. }
  43. }
  44. // 如果启用了 Waffo 支付,添加到支付方法列表
  45. enableWaffo := setting.WaffoEnabled &&
  46. ((!setting.WaffoSandbox &&
  47. setting.WaffoApiKey != "" &&
  48. setting.WaffoPrivateKey != "" &&
  49. setting.WaffoPublicCert != "") ||
  50. (setting.WaffoSandbox &&
  51. setting.WaffoSandboxApiKey != "" &&
  52. setting.WaffoSandboxPrivateKey != "" &&
  53. setting.WaffoSandboxPublicCert != ""))
  54. if enableWaffo {
  55. hasWaffo := false
  56. for _, method := range payMethods {
  57. if method["type"] == "waffo" {
  58. hasWaffo = true
  59. break
  60. }
  61. }
  62. if !hasWaffo {
  63. waffoMethod := map[string]string{
  64. "name": "Waffo (Global Payment)",
  65. "type": "waffo",
  66. "color": "rgba(var(--semi-blue-5), 1)",
  67. "min_topup": strconv.Itoa(setting.WaffoMinTopUp),
  68. }
  69. payMethods = append(payMethods, waffoMethod)
  70. }
  71. }
  72. data := gin.H{
  73. "enable_online_topup": operation_setting.PayAddress != "" && operation_setting.EpayId != "" && operation_setting.EpayKey != "",
  74. "enable_stripe_topup": setting.StripeApiSecret != "" && setting.StripeWebhookSecret != "" && setting.StripePriceId != "",
  75. "enable_creem_topup": setting.CreemApiKey != "" && setting.CreemProducts != "[]",
  76. "enable_waffo_topup": enableWaffo,
  77. "waffo_pay_methods": func() interface{} {
  78. if enableWaffo {
  79. return setting.GetWaffoPayMethods()
  80. }
  81. return nil
  82. }(),
  83. "creem_products": setting.CreemProducts,
  84. "pay_methods": payMethods,
  85. "min_topup": operation_setting.MinTopUp,
  86. "stripe_min_topup": setting.StripeMinTopUp,
  87. "waffo_min_topup": setting.WaffoMinTopUp,
  88. "amount_options": operation_setting.GetPaymentSetting().AmountOptions,
  89. "discount": operation_setting.GetPaymentSetting().AmountDiscount,
  90. }
  91. common.ApiSuccess(c, data)
  92. }
  93. type EpayRequest struct {
  94. Amount int64 `json:"amount"`
  95. PaymentMethod string `json:"payment_method"`
  96. }
  97. type AmountRequest struct {
  98. Amount int64 `json:"amount"`
  99. }
  100. func GetEpayClient() *epay.Client {
  101. if operation_setting.PayAddress == "" || operation_setting.EpayId == "" || operation_setting.EpayKey == "" {
  102. return nil
  103. }
  104. withUrl, err := epay.NewClient(&epay.Config{
  105. PartnerID: operation_setting.EpayId,
  106. Key: operation_setting.EpayKey,
  107. }, operation_setting.PayAddress)
  108. if err != nil {
  109. return nil
  110. }
  111. return withUrl
  112. }
  113. func getPayMoney(amount int64, group string) float64 {
  114. dAmount := decimal.NewFromInt(amount)
  115. // 充值金额以“展示类型”为准:
  116. // - USD/CNY: 前端传 amount 为金额单位;TOKENS: 前端传 tokens,需要换成 USD 金额
  117. if operation_setting.GetQuotaDisplayType() == operation_setting.QuotaDisplayTypeTokens {
  118. dQuotaPerUnit := decimal.NewFromFloat(common.QuotaPerUnit)
  119. dAmount = dAmount.Div(dQuotaPerUnit)
  120. }
  121. topupGroupRatio := common.GetTopupGroupRatio(group)
  122. if topupGroupRatio == 0 {
  123. topupGroupRatio = 1
  124. }
  125. dTopupGroupRatio := decimal.NewFromFloat(topupGroupRatio)
  126. dPrice := decimal.NewFromFloat(operation_setting.Price)
  127. // apply optional preset discount by the original request amount (if configured), default 1.0
  128. discount := 1.0
  129. if ds, ok := operation_setting.GetPaymentSetting().AmountDiscount[int(amount)]; ok {
  130. if ds > 0 {
  131. discount = ds
  132. }
  133. }
  134. dDiscount := decimal.NewFromFloat(discount)
  135. payMoney := dAmount.Mul(dPrice).Mul(dTopupGroupRatio).Mul(dDiscount)
  136. return payMoney.InexactFloat64()
  137. }
  138. func getMinTopup() int64 {
  139. minTopup := operation_setting.MinTopUp
  140. if operation_setting.GetQuotaDisplayType() == operation_setting.QuotaDisplayTypeTokens {
  141. dMinTopup := decimal.NewFromInt(int64(minTopup))
  142. dQuotaPerUnit := decimal.NewFromFloat(common.QuotaPerUnit)
  143. minTopup = int(dMinTopup.Mul(dQuotaPerUnit).IntPart())
  144. }
  145. return int64(minTopup)
  146. }
  147. func RequestEpay(c *gin.Context) {
  148. var req EpayRequest
  149. err := c.ShouldBindJSON(&req)
  150. if err != nil {
  151. c.JSON(200, gin.H{"message": "error", "data": "参数错误"})
  152. return
  153. }
  154. if req.Amount < getMinTopup() {
  155. c.JSON(200, gin.H{"message": "error", "data": fmt.Sprintf("充值数量不能小于 %d", getMinTopup())})
  156. return
  157. }
  158. id := c.GetInt("id")
  159. group, err := model.GetUserGroup(id, true)
  160. if err != nil {
  161. c.JSON(200, gin.H{"message": "error", "data": "获取用户分组失败"})
  162. return
  163. }
  164. payMoney := getPayMoney(req.Amount, group)
  165. if payMoney < 0.01 {
  166. c.JSON(200, gin.H{"message": "error", "data": "充值金额过低"})
  167. return
  168. }
  169. if !operation_setting.ContainsPayMethod(req.PaymentMethod) {
  170. c.JSON(200, gin.H{"message": "error", "data": "支付方式不存在"})
  171. return
  172. }
  173. callBackAddress := service.GetCallbackAddress()
  174. returnUrl, _ := url.Parse(system_setting.ServerAddress + "/console/log")
  175. notifyUrl, _ := url.Parse(callBackAddress + "/api/user/epay/notify")
  176. tradeNo := fmt.Sprintf("%s%d", common.GetRandomString(6), time.Now().Unix())
  177. tradeNo = fmt.Sprintf("USR%dNO%s", id, tradeNo)
  178. client := GetEpayClient()
  179. if client == nil {
  180. c.JSON(200, gin.H{"message": "error", "data": "当前管理员未配置支付信息"})
  181. return
  182. }
  183. uri, params, err := client.Purchase(&epay.PurchaseArgs{
  184. Type: req.PaymentMethod,
  185. ServiceTradeNo: tradeNo,
  186. Name: fmt.Sprintf("TUC%d", req.Amount),
  187. Money: strconv.FormatFloat(payMoney, 'f', 2, 64),
  188. Device: epay.PC,
  189. NotifyUrl: notifyUrl,
  190. ReturnUrl: returnUrl,
  191. })
  192. if err != nil {
  193. c.JSON(200, gin.H{"message": "error", "data": "拉起支付失败"})
  194. return
  195. }
  196. amount := req.Amount
  197. if operation_setting.GetQuotaDisplayType() == operation_setting.QuotaDisplayTypeTokens {
  198. dAmount := decimal.NewFromInt(int64(amount))
  199. dQuotaPerUnit := decimal.NewFromFloat(common.QuotaPerUnit)
  200. amount = dAmount.Div(dQuotaPerUnit).IntPart()
  201. }
  202. topUp := &model.TopUp{
  203. UserId: id,
  204. Amount: amount,
  205. Money: payMoney,
  206. TradeNo: tradeNo,
  207. PaymentMethod: req.PaymentMethod,
  208. CreateTime: time.Now().Unix(),
  209. Status: "pending",
  210. }
  211. err = topUp.Insert()
  212. if err != nil {
  213. c.JSON(200, gin.H{"message": "error", "data": "创建订单失败"})
  214. return
  215. }
  216. c.JSON(200, gin.H{"message": "success", "data": params, "url": uri})
  217. }
  218. // tradeNo lock
  219. var orderLocks sync.Map
  220. var createLock sync.Mutex
  221. // refCountedMutex 带引用计数的互斥锁,确保最后一个使用者才从 map 中删除
  222. type refCountedMutex struct {
  223. mu sync.Mutex
  224. refCount int
  225. }
  226. // LockOrder 尝试对给定订单号加锁
  227. func LockOrder(tradeNo string) {
  228. createLock.Lock()
  229. var rcm *refCountedMutex
  230. if v, ok := orderLocks.Load(tradeNo); ok {
  231. rcm = v.(*refCountedMutex)
  232. } else {
  233. rcm = &refCountedMutex{}
  234. orderLocks.Store(tradeNo, rcm)
  235. }
  236. rcm.refCount++
  237. createLock.Unlock()
  238. rcm.mu.Lock()
  239. }
  240. // UnlockOrder 释放给定订单号的锁
  241. func UnlockOrder(tradeNo string) {
  242. v, ok := orderLocks.Load(tradeNo)
  243. if !ok {
  244. return
  245. }
  246. rcm := v.(*refCountedMutex)
  247. rcm.mu.Unlock()
  248. createLock.Lock()
  249. rcm.refCount--
  250. if rcm.refCount == 0 {
  251. orderLocks.Delete(tradeNo)
  252. }
  253. createLock.Unlock()
  254. }
  255. func EpayNotify(c *gin.Context) {
  256. var params map[string]string
  257. if c.Request.Method == "POST" {
  258. // POST 请求:从 POST body 解析参数
  259. if err := c.Request.ParseForm(); err != nil {
  260. log.Println("易支付回调POST解析失败:", err)
  261. _, _ = c.Writer.Write([]byte("fail"))
  262. return
  263. }
  264. params = lo.Reduce(lo.Keys(c.Request.PostForm), func(r map[string]string, t string, i int) map[string]string {
  265. r[t] = c.Request.PostForm.Get(t)
  266. return r
  267. }, map[string]string{})
  268. } else {
  269. // GET 请求:从 URL Query 解析参数
  270. params = lo.Reduce(lo.Keys(c.Request.URL.Query()), func(r map[string]string, t string, i int) map[string]string {
  271. r[t] = c.Request.URL.Query().Get(t)
  272. return r
  273. }, map[string]string{})
  274. }
  275. if len(params) == 0 {
  276. log.Println("易支付回调参数为空")
  277. _, _ = c.Writer.Write([]byte("fail"))
  278. return
  279. }
  280. client := GetEpayClient()
  281. if client == nil {
  282. log.Println("易支付回调失败 未找到配置信息")
  283. _, err := c.Writer.Write([]byte("fail"))
  284. if err != nil {
  285. log.Println("易支付回调写入失败")
  286. }
  287. return
  288. }
  289. verifyInfo, err := client.Verify(params)
  290. if err == nil && verifyInfo.VerifyStatus {
  291. _, err := c.Writer.Write([]byte("success"))
  292. if err != nil {
  293. log.Println("易支付回调写入失败")
  294. }
  295. } else {
  296. _, err := c.Writer.Write([]byte("fail"))
  297. if err != nil {
  298. log.Println("易支付回调写入失败")
  299. }
  300. log.Println("易支付回调签名验证失败")
  301. return
  302. }
  303. if verifyInfo.TradeStatus == epay.StatusTradeSuccess {
  304. log.Println(verifyInfo)
  305. LockOrder(verifyInfo.ServiceTradeNo)
  306. defer UnlockOrder(verifyInfo.ServiceTradeNo)
  307. topUp := model.GetTopUpByTradeNo(verifyInfo.ServiceTradeNo)
  308. if topUp == nil {
  309. log.Printf("易支付回调未找到订单: %v", verifyInfo)
  310. return
  311. }
  312. if topUp.Status == "pending" {
  313. topUp.Status = "success"
  314. err := topUp.Update()
  315. if err != nil {
  316. log.Printf("易支付回调更新订单失败: %v", topUp)
  317. return
  318. }
  319. //user, _ := model.GetUserById(topUp.UserId, false)
  320. //user.Quota += topUp.Amount * 500000
  321. dAmount := decimal.NewFromInt(int64(topUp.Amount))
  322. dQuotaPerUnit := decimal.NewFromFloat(common.QuotaPerUnit)
  323. quotaToAdd := int(dAmount.Mul(dQuotaPerUnit).IntPart())
  324. err = model.IncreaseUserQuota(topUp.UserId, quotaToAdd, true)
  325. if err != nil {
  326. log.Printf("易支付回调更新用户失败: %v", topUp)
  327. return
  328. }
  329. log.Printf("易支付回调更新用户成功 %v", topUp)
  330. model.RecordLog(topUp.UserId, model.LogTypeTopup, fmt.Sprintf("使用在线充值成功,充值金额: %v,支付金额:%f", logger.LogQuota(quotaToAdd), topUp.Money))
  331. }
  332. } else {
  333. log.Printf("易支付异常回调: %v", verifyInfo)
  334. }
  335. }
  336. func RequestAmount(c *gin.Context) {
  337. var req AmountRequest
  338. err := c.ShouldBindJSON(&req)
  339. if err != nil {
  340. c.JSON(200, gin.H{"message": "error", "data": "参数错误"})
  341. return
  342. }
  343. if req.Amount < getMinTopup() {
  344. c.JSON(200, gin.H{"message": "error", "data": fmt.Sprintf("充值数量不能小于 %d", getMinTopup())})
  345. return
  346. }
  347. id := c.GetInt("id")
  348. group, err := model.GetUserGroup(id, true)
  349. if err != nil {
  350. c.JSON(200, gin.H{"message": "error", "data": "获取用户分组失败"})
  351. return
  352. }
  353. payMoney := getPayMoney(req.Amount, group)
  354. if payMoney <= 0.01 {
  355. c.JSON(200, gin.H{"message": "error", "data": "充值金额过低"})
  356. return
  357. }
  358. c.JSON(200, gin.H{"message": "success", "data": strconv.FormatFloat(payMoney, 'f', 2, 64)})
  359. }
  360. func GetUserTopUps(c *gin.Context) {
  361. userId := c.GetInt("id")
  362. pageInfo := common.GetPageQuery(c)
  363. keyword := c.Query("keyword")
  364. var (
  365. topups []*model.TopUp
  366. total int64
  367. err error
  368. )
  369. if keyword != "" {
  370. topups, total, err = model.SearchUserTopUps(userId, keyword, pageInfo)
  371. } else {
  372. topups, total, err = model.GetUserTopUps(userId, pageInfo)
  373. }
  374. if err != nil {
  375. common.ApiError(c, err)
  376. return
  377. }
  378. pageInfo.SetTotal(int(total))
  379. pageInfo.SetItems(topups)
  380. common.ApiSuccess(c, pageInfo)
  381. }
  382. // GetAllTopUps 管理员获取全平台充值记录
  383. func GetAllTopUps(c *gin.Context) {
  384. pageInfo := common.GetPageQuery(c)
  385. keyword := c.Query("keyword")
  386. var (
  387. topups []*model.TopUp
  388. total int64
  389. err error
  390. )
  391. if keyword != "" {
  392. topups, total, err = model.SearchAllTopUps(keyword, pageInfo)
  393. } else {
  394. topups, total, err = model.GetAllTopUps(pageInfo)
  395. }
  396. if err != nil {
  397. common.ApiError(c, err)
  398. return
  399. }
  400. pageInfo.SetTotal(int(total))
  401. pageInfo.SetItems(topups)
  402. common.ApiSuccess(c, pageInfo)
  403. }
  404. type AdminCompleteTopupRequest struct {
  405. TradeNo string `json:"trade_no"`
  406. }
  407. // AdminCompleteTopUp 管理员补单接口
  408. func AdminCompleteTopUp(c *gin.Context) {
  409. var req AdminCompleteTopupRequest
  410. if err := c.ShouldBindJSON(&req); err != nil || req.TradeNo == "" {
  411. common.ApiErrorMsg(c, "参数错误")
  412. return
  413. }
  414. // 订单级互斥,防止并发补单
  415. LockOrder(req.TradeNo)
  416. defer UnlockOrder(req.TradeNo)
  417. if err := model.ManualCompleteTopUp(req.TradeNo); err != nil {
  418. common.ApiError(c, err)
  419. return
  420. }
  421. common.ApiSuccess(c, nil)
  422. }