topup.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. package controller
  2. import (
  3. "fmt"
  4. "log"
  5. "net/url"
  6. "one-api/common"
  7. "one-api/logger"
  8. "one-api/model"
  9. "one-api/service"
  10. "one-api/setting"
  11. "one-api/setting/operation_setting"
  12. "one-api/setting/system_setting"
  13. "strconv"
  14. "sync"
  15. "time"
  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. data := gin.H{
  45. "enable_online_topup": operation_setting.PayAddress != "" && operation_setting.EpayId != "" && operation_setting.EpayKey != "",
  46. "enable_stripe_topup": setting.StripeApiSecret != "" && setting.StripeWebhookSecret != "" && setting.StripePriceId != "",
  47. "pay_methods": payMethods,
  48. "min_topup": operation_setting.MinTopUp,
  49. "stripe_min_topup": setting.StripeMinTopUp,
  50. "amount_options": operation_setting.GetPaymentSetting().AmountOptions,
  51. "discount": operation_setting.GetPaymentSetting().AmountDiscount,
  52. }
  53. common.ApiSuccess(c, data)
  54. }
  55. type EpayRequest struct {
  56. Amount int64 `json:"amount"`
  57. PaymentMethod string `json:"payment_method"`
  58. TopUpCode string `json:"top_up_code"`
  59. }
  60. type AmountRequest struct {
  61. Amount int64 `json:"amount"`
  62. TopUpCode string `json:"top_up_code"`
  63. }
  64. func GetEpayClient() *epay.Client {
  65. if operation_setting.PayAddress == "" || operation_setting.EpayId == "" || operation_setting.EpayKey == "" {
  66. return nil
  67. }
  68. withUrl, err := epay.NewClient(&epay.Config{
  69. PartnerID: operation_setting.EpayId,
  70. Key: operation_setting.EpayKey,
  71. }, operation_setting.PayAddress)
  72. if err != nil {
  73. return nil
  74. }
  75. return withUrl
  76. }
  77. func getPayMoney(amount int64, group string) float64 {
  78. dAmount := decimal.NewFromInt(amount)
  79. // 充值金额以“展示类型”为准:
  80. // - USD/CNY: 前端传 amount 为金额单位;TOKENS: 前端传 tokens,需要换成 USD 金额
  81. if operation_setting.GetQuotaDisplayType() == operation_setting.QuotaDisplayTypeTokens {
  82. dQuotaPerUnit := decimal.NewFromFloat(common.QuotaPerUnit)
  83. dAmount = dAmount.Div(dQuotaPerUnit)
  84. }
  85. topupGroupRatio := common.GetTopupGroupRatio(group)
  86. if topupGroupRatio == 0 {
  87. topupGroupRatio = 1
  88. }
  89. dTopupGroupRatio := decimal.NewFromFloat(topupGroupRatio)
  90. dPrice := decimal.NewFromFloat(operation_setting.Price)
  91. // apply optional preset discount by the original request amount (if configured), default 1.0
  92. discount := 1.0
  93. if ds, ok := operation_setting.GetPaymentSetting().AmountDiscount[int(amount)]; ok {
  94. if ds > 0 {
  95. discount = ds
  96. }
  97. }
  98. dDiscount := decimal.NewFromFloat(discount)
  99. payMoney := dAmount.Mul(dPrice).Mul(dTopupGroupRatio).Mul(dDiscount)
  100. return payMoney.InexactFloat64()
  101. }
  102. func getMinTopup() int64 {
  103. minTopup := operation_setting.MinTopUp
  104. if operation_setting.GetQuotaDisplayType() == operation_setting.QuotaDisplayTypeTokens {
  105. dMinTopup := decimal.NewFromInt(int64(minTopup))
  106. dQuotaPerUnit := decimal.NewFromFloat(common.QuotaPerUnit)
  107. minTopup = int(dMinTopup.Mul(dQuotaPerUnit).IntPart())
  108. }
  109. return int64(minTopup)
  110. }
  111. func RequestEpay(c *gin.Context) {
  112. var req EpayRequest
  113. err := c.ShouldBindJSON(&req)
  114. if err != nil {
  115. c.JSON(200, gin.H{"message": "error", "data": "参数错误"})
  116. return
  117. }
  118. if req.Amount < getMinTopup() {
  119. c.JSON(200, gin.H{"message": "error", "data": fmt.Sprintf("充值数量不能小于 %d", getMinTopup())})
  120. return
  121. }
  122. id := c.GetInt("id")
  123. group, err := model.GetUserGroup(id, true)
  124. if err != nil {
  125. c.JSON(200, gin.H{"message": "error", "data": "获取用户分组失败"})
  126. return
  127. }
  128. payMoney := getPayMoney(req.Amount, group)
  129. if payMoney < 0.01 {
  130. c.JSON(200, gin.H{"message": "error", "data": "充值金额过低"})
  131. return
  132. }
  133. if !operation_setting.ContainsPayMethod(req.PaymentMethod) {
  134. c.JSON(200, gin.H{"message": "error", "data": "支付方式不存在"})
  135. return
  136. }
  137. callBackAddress := service.GetCallbackAddress()
  138. returnUrl, _ := url.Parse(system_setting.ServerAddress + "/console/log")
  139. notifyUrl, _ := url.Parse(callBackAddress + "/api/user/epay/notify")
  140. tradeNo := fmt.Sprintf("%s%d", common.GetRandomString(6), time.Now().Unix())
  141. tradeNo = fmt.Sprintf("USR%dNO%s", id, tradeNo)
  142. client := GetEpayClient()
  143. if client == nil {
  144. c.JSON(200, gin.H{"message": "error", "data": "当前管理员未配置支付信息"})
  145. return
  146. }
  147. uri, params, err := client.Purchase(&epay.PurchaseArgs{
  148. Type: req.PaymentMethod,
  149. ServiceTradeNo: tradeNo,
  150. Name: fmt.Sprintf("TUC%d", req.Amount),
  151. Money: strconv.FormatFloat(payMoney, 'f', 2, 64),
  152. Device: epay.PC,
  153. NotifyUrl: notifyUrl,
  154. ReturnUrl: returnUrl,
  155. })
  156. if err != nil {
  157. c.JSON(200, gin.H{"message": "error", "data": "拉起支付失败"})
  158. return
  159. }
  160. amount := req.Amount
  161. if operation_setting.GetQuotaDisplayType() == operation_setting.QuotaDisplayTypeTokens {
  162. dAmount := decimal.NewFromInt(int64(amount))
  163. dQuotaPerUnit := decimal.NewFromFloat(common.QuotaPerUnit)
  164. amount = dAmount.Div(dQuotaPerUnit).IntPart()
  165. }
  166. topUp := &model.TopUp{
  167. UserId: id,
  168. Amount: amount,
  169. Money: payMoney,
  170. TradeNo: tradeNo,
  171. PaymentMethod: req.PaymentMethod,
  172. CreateTime: time.Now().Unix(),
  173. Status: "pending",
  174. }
  175. err = topUp.Insert()
  176. if err != nil {
  177. c.JSON(200, gin.H{"message": "error", "data": "创建订单失败"})
  178. return
  179. }
  180. c.JSON(200, gin.H{"message": "success", "data": params, "url": uri})
  181. }
  182. // tradeNo lock
  183. var orderLocks sync.Map
  184. var createLock sync.Mutex
  185. // LockOrder 尝试对给定订单号加锁
  186. func LockOrder(tradeNo string) {
  187. lock, ok := orderLocks.Load(tradeNo)
  188. if !ok {
  189. createLock.Lock()
  190. defer createLock.Unlock()
  191. lock, ok = orderLocks.Load(tradeNo)
  192. if !ok {
  193. lock = new(sync.Mutex)
  194. orderLocks.Store(tradeNo, lock)
  195. }
  196. }
  197. lock.(*sync.Mutex).Lock()
  198. }
  199. // UnlockOrder 释放给定订单号的锁
  200. func UnlockOrder(tradeNo string) {
  201. lock, ok := orderLocks.Load(tradeNo)
  202. if ok {
  203. lock.(*sync.Mutex).Unlock()
  204. }
  205. }
  206. func EpayNotify(c *gin.Context) {
  207. params := lo.Reduce(lo.Keys(c.Request.URL.Query()), func(r map[string]string, t string, i int) map[string]string {
  208. r[t] = c.Request.URL.Query().Get(t)
  209. return r
  210. }, map[string]string{})
  211. client := GetEpayClient()
  212. if client == nil {
  213. log.Println("易支付回调失败 未找到配置信息")
  214. _, err := c.Writer.Write([]byte("fail"))
  215. if err != nil {
  216. log.Println("易支付回调写入失败")
  217. }
  218. return
  219. }
  220. verifyInfo, err := client.Verify(params)
  221. if err == nil && verifyInfo.VerifyStatus {
  222. _, err := c.Writer.Write([]byte("success"))
  223. if err != nil {
  224. log.Println("易支付回调写入失败")
  225. }
  226. } else {
  227. _, err := c.Writer.Write([]byte("fail"))
  228. if err != nil {
  229. log.Println("易支付回调写入失败")
  230. }
  231. log.Println("易支付回调签名验证失败")
  232. return
  233. }
  234. if verifyInfo.TradeStatus == epay.StatusTradeSuccess {
  235. log.Println(verifyInfo)
  236. LockOrder(verifyInfo.ServiceTradeNo)
  237. defer UnlockOrder(verifyInfo.ServiceTradeNo)
  238. topUp := model.GetTopUpByTradeNo(verifyInfo.ServiceTradeNo)
  239. if topUp == nil {
  240. log.Printf("易支付回调未找到订单: %v", verifyInfo)
  241. return
  242. }
  243. if topUp.Status == "pending" {
  244. topUp.Status = "success"
  245. err := topUp.Update()
  246. if err != nil {
  247. log.Printf("易支付回调更新订单失败: %v", topUp)
  248. return
  249. }
  250. //user, _ := model.GetUserById(topUp.UserId, false)
  251. //user.Quota += topUp.Amount * 500000
  252. dAmount := decimal.NewFromInt(int64(topUp.Amount))
  253. dQuotaPerUnit := decimal.NewFromFloat(common.QuotaPerUnit)
  254. quotaToAdd := int(dAmount.Mul(dQuotaPerUnit).IntPart())
  255. err = model.IncreaseUserQuota(topUp.UserId, quotaToAdd, true)
  256. if err != nil {
  257. log.Printf("易支付回调更新用户失败: %v", topUp)
  258. return
  259. }
  260. log.Printf("易支付回调更新用户成功 %v", topUp)
  261. model.RecordLog(topUp.UserId, model.LogTypeTopup, fmt.Sprintf("使用在线充值成功,充值金额: %v,支付金额:%f", logger.LogQuota(quotaToAdd), topUp.Money))
  262. }
  263. } else {
  264. log.Printf("易支付异常回调: %v", verifyInfo)
  265. }
  266. }
  267. func RequestAmount(c *gin.Context) {
  268. var req AmountRequest
  269. err := c.ShouldBindJSON(&req)
  270. if err != nil {
  271. c.JSON(200, gin.H{"message": "error", "data": "参数错误"})
  272. return
  273. }
  274. if req.Amount < getMinTopup() {
  275. c.JSON(200, gin.H{"message": "error", "data": fmt.Sprintf("充值数量不能小于 %d", getMinTopup())})
  276. return
  277. }
  278. id := c.GetInt("id")
  279. group, err := model.GetUserGroup(id, true)
  280. if err != nil {
  281. c.JSON(200, gin.H{"message": "error", "data": "获取用户分组失败"})
  282. return
  283. }
  284. payMoney := getPayMoney(req.Amount, group)
  285. if payMoney <= 0.01 {
  286. c.JSON(200, gin.H{"message": "error", "data": "充值金额过低"})
  287. return
  288. }
  289. c.JSON(200, gin.H{"message": "success", "data": strconv.FormatFloat(payMoney, 'f', 2, 64)})
  290. }
  291. func GetUserTopUps(c *gin.Context) {
  292. userId := c.GetInt("id")
  293. pageInfo := common.GetPageQuery(c)
  294. keyword := c.Query("keyword")
  295. var (
  296. topups []*model.TopUp
  297. total int64
  298. err error
  299. )
  300. if keyword != "" {
  301. topups, total, err = model.SearchUserTopUps(userId, keyword, pageInfo)
  302. } else {
  303. topups, total, err = model.GetUserTopUps(userId, pageInfo)
  304. }
  305. if err != nil {
  306. common.ApiError(c, err)
  307. return
  308. }
  309. pageInfo.SetTotal(int(total))
  310. pageInfo.SetItems(topups)
  311. common.ApiSuccess(c, pageInfo)
  312. }
  313. // GetAllTopUps 管理员获取全平台充值记录
  314. func GetAllTopUps(c *gin.Context) {
  315. pageInfo := common.GetPageQuery(c)
  316. keyword := c.Query("keyword")
  317. var (
  318. topups []*model.TopUp
  319. total int64
  320. err error
  321. )
  322. if keyword != "" {
  323. topups, total, err = model.SearchAllTopUps(keyword, pageInfo)
  324. } else {
  325. topups, total, err = model.GetAllTopUps(pageInfo)
  326. }
  327. if err != nil {
  328. common.ApiError(c, err)
  329. return
  330. }
  331. pageInfo.SetTotal(int(total))
  332. pageInfo.SetItems(topups)
  333. common.ApiSuccess(c, pageInfo)
  334. }
  335. type AdminCompleteTopupRequest struct {
  336. TradeNo string `json:"trade_no"`
  337. }
  338. // AdminCompleteTopUp 管理员补单接口
  339. func AdminCompleteTopUp(c *gin.Context) {
  340. var req AdminCompleteTopupRequest
  341. if err := c.ShouldBindJSON(&req); err != nil || req.TradeNo == "" {
  342. common.ApiErrorMsg(c, "参数错误")
  343. return
  344. }
  345. // 订单级互斥,防止并发补单
  346. LockOrder(req.TradeNo)
  347. defer UnlockOrder(req.TradeNo)
  348. if err := model.ManualCompleteTopUp(req.TradeNo); err != nil {
  349. common.ApiError(c, err)
  350. return
  351. }
  352. common.ApiSuccess(c, nil)
  353. }