topup.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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. "strconv"
  13. "sync"
  14. "time"
  15. "github.com/Calcium-Ion/go-epay/epay"
  16. "github.com/gin-gonic/gin"
  17. "github.com/samber/lo"
  18. "github.com/shopspring/decimal"
  19. )
  20. func GetTopUpInfo(c *gin.Context) {
  21. // 获取支付方式
  22. payMethods := operation_setting.PayMethods
  23. // 如果启用了 Stripe 支付,添加到支付方法列表
  24. if setting.StripeApiSecret != "" && setting.StripeWebhookSecret != "" && setting.StripePriceId != "" {
  25. // 检查是否已经包含 Stripe
  26. hasStripe := false
  27. for _, method := range payMethods {
  28. if method["type"] == "stripe" {
  29. hasStripe = true
  30. break
  31. }
  32. }
  33. if !hasStripe {
  34. stripeMethod := map[string]string{
  35. "name": "Stripe",
  36. "type": "stripe",
  37. "color": "rgba(var(--semi-purple-5), 1)",
  38. "min_topup": strconv.Itoa(setting.StripeMinTopUp),
  39. }
  40. payMethods = append(payMethods, stripeMethod)
  41. }
  42. }
  43. data := gin.H{
  44. "enable_online_topup": operation_setting.PayAddress != "" && operation_setting.EpayId != "" && operation_setting.EpayKey != "",
  45. "enable_stripe_topup": setting.StripeApiSecret != "" && setting.StripeWebhookSecret != "" && setting.StripePriceId != "",
  46. "pay_methods": payMethods,
  47. "min_topup": operation_setting.MinTopUp,
  48. "stripe_min_topup": setting.StripeMinTopUp,
  49. "amount_options": operation_setting.GetPaymentSetting().AmountOptions,
  50. "discount": operation_setting.GetPaymentSetting().AmountDiscount,
  51. }
  52. common.ApiSuccess(c, data)
  53. }
  54. type EpayRequest struct {
  55. Amount int64 `json:"amount"`
  56. PaymentMethod string `json:"payment_method"`
  57. TopUpCode string `json:"top_up_code"`
  58. }
  59. type AmountRequest struct {
  60. Amount int64 `json:"amount"`
  61. TopUpCode string `json:"top_up_code"`
  62. }
  63. func GetEpayClient() *epay.Client {
  64. if operation_setting.PayAddress == "" || operation_setting.EpayId == "" || operation_setting.EpayKey == "" {
  65. return nil
  66. }
  67. withUrl, err := epay.NewClient(&epay.Config{
  68. PartnerID: operation_setting.EpayId,
  69. Key: operation_setting.EpayKey,
  70. }, operation_setting.PayAddress)
  71. if err != nil {
  72. return nil
  73. }
  74. return withUrl
  75. }
  76. func getPayMoney(amount int64, group string) float64 {
  77. dAmount := decimal.NewFromInt(amount)
  78. if !common.DisplayInCurrencyEnabled {
  79. dQuotaPerUnit := decimal.NewFromFloat(common.QuotaPerUnit)
  80. dAmount = dAmount.Div(dQuotaPerUnit)
  81. }
  82. topupGroupRatio := common.GetTopupGroupRatio(group)
  83. if topupGroupRatio == 0 {
  84. topupGroupRatio = 1
  85. }
  86. dTopupGroupRatio := decimal.NewFromFloat(topupGroupRatio)
  87. dPrice := decimal.NewFromFloat(operation_setting.Price)
  88. // apply optional preset discount by the original request amount (if configured), default 1.0
  89. discount := 1.0
  90. if ds, ok := operation_setting.GetPaymentSetting().AmountDiscount[int(amount)]; ok {
  91. if ds > 0 {
  92. discount = ds
  93. }
  94. }
  95. dDiscount := decimal.NewFromFloat(discount)
  96. payMoney := dAmount.Mul(dPrice).Mul(dTopupGroupRatio).Mul(dDiscount)
  97. return payMoney.InexactFloat64()
  98. }
  99. func getMinTopup() int64 {
  100. minTopup := operation_setting.MinTopUp
  101. if !common.DisplayInCurrencyEnabled {
  102. dMinTopup := decimal.NewFromInt(int64(minTopup))
  103. dQuotaPerUnit := decimal.NewFromFloat(common.QuotaPerUnit)
  104. minTopup = int(dMinTopup.Mul(dQuotaPerUnit).IntPart())
  105. }
  106. return int64(minTopup)
  107. }
  108. func RequestEpay(c *gin.Context) {
  109. var req EpayRequest
  110. err := c.ShouldBindJSON(&req)
  111. if err != nil {
  112. c.JSON(200, gin.H{"message": "error", "data": "参数错误"})
  113. return
  114. }
  115. if req.Amount < getMinTopup() {
  116. c.JSON(200, gin.H{"message": "error", "data": fmt.Sprintf("充值数量不能小于 %d", getMinTopup())})
  117. return
  118. }
  119. id := c.GetInt("id")
  120. group, err := model.GetUserGroup(id, true)
  121. if err != nil {
  122. c.JSON(200, gin.H{"message": "error", "data": "获取用户分组失败"})
  123. return
  124. }
  125. payMoney := getPayMoney(req.Amount, group)
  126. if payMoney < 0.01 {
  127. c.JSON(200, gin.H{"message": "error", "data": "充值金额过低"})
  128. return
  129. }
  130. if !operation_setting.ContainsPayMethod(req.PaymentMethod) {
  131. c.JSON(200, gin.H{"message": "error", "data": "支付方式不存在"})
  132. return
  133. }
  134. callBackAddress := service.GetCallbackAddress()
  135. returnUrl, _ := url.Parse(setting.ServerAddress + "/console/log")
  136. notifyUrl, _ := url.Parse(callBackAddress + "/api/user/epay/notify")
  137. tradeNo := fmt.Sprintf("%s%d", common.GetRandomString(6), time.Now().Unix())
  138. tradeNo = fmt.Sprintf("USR%dNO%s", id, tradeNo)
  139. client := GetEpayClient()
  140. if client == nil {
  141. c.JSON(200, gin.H{"message": "error", "data": "当前管理员未配置支付信息"})
  142. return
  143. }
  144. uri, params, err := client.Purchase(&epay.PurchaseArgs{
  145. Type: req.PaymentMethod,
  146. ServiceTradeNo: tradeNo,
  147. Name: fmt.Sprintf("TUC%d", req.Amount),
  148. Money: strconv.FormatFloat(payMoney, 'f', 2, 64),
  149. Device: epay.PC,
  150. NotifyUrl: notifyUrl,
  151. ReturnUrl: returnUrl,
  152. })
  153. if err != nil {
  154. c.JSON(200, gin.H{"message": "error", "data": "拉起支付失败"})
  155. return
  156. }
  157. amount := req.Amount
  158. if !common.DisplayInCurrencyEnabled {
  159. dAmount := decimal.NewFromInt(int64(amount))
  160. dQuotaPerUnit := decimal.NewFromFloat(common.QuotaPerUnit)
  161. amount = dAmount.Div(dQuotaPerUnit).IntPart()
  162. }
  163. topUp := &model.TopUp{
  164. UserId: id,
  165. Amount: amount,
  166. Money: payMoney,
  167. TradeNo: tradeNo,
  168. CreateTime: time.Now().Unix(),
  169. Status: "pending",
  170. }
  171. err = topUp.Insert()
  172. if err != nil {
  173. c.JSON(200, gin.H{"message": "error", "data": "创建订单失败"})
  174. return
  175. }
  176. c.JSON(200, gin.H{"message": "success", "data": params, "url": uri})
  177. }
  178. // tradeNo lock
  179. var orderLocks sync.Map
  180. var createLock sync.Mutex
  181. // LockOrder 尝试对给定订单号加锁
  182. func LockOrder(tradeNo string) {
  183. lock, ok := orderLocks.Load(tradeNo)
  184. if !ok {
  185. createLock.Lock()
  186. defer createLock.Unlock()
  187. lock, ok = orderLocks.Load(tradeNo)
  188. if !ok {
  189. lock = new(sync.Mutex)
  190. orderLocks.Store(tradeNo, lock)
  191. }
  192. }
  193. lock.(*sync.Mutex).Lock()
  194. }
  195. // UnlockOrder 释放给定订单号的锁
  196. func UnlockOrder(tradeNo string) {
  197. lock, ok := orderLocks.Load(tradeNo)
  198. if ok {
  199. lock.(*sync.Mutex).Unlock()
  200. }
  201. }
  202. func EpayNotify(c *gin.Context) {
  203. params := lo.Reduce(lo.Keys(c.Request.URL.Query()), func(r map[string]string, t string, i int) map[string]string {
  204. r[t] = c.Request.URL.Query().Get(t)
  205. return r
  206. }, map[string]string{})
  207. client := GetEpayClient()
  208. if client == nil {
  209. log.Println("易支付回调失败 未找到配置信息")
  210. _, err := c.Writer.Write([]byte("fail"))
  211. if err != nil {
  212. log.Println("易支付回调写入失败")
  213. return
  214. }
  215. }
  216. verifyInfo, err := client.Verify(params)
  217. if err == nil && verifyInfo.VerifyStatus {
  218. _, err := c.Writer.Write([]byte("success"))
  219. if err != nil {
  220. log.Println("易支付回调写入失败")
  221. }
  222. } else {
  223. _, err := c.Writer.Write([]byte("fail"))
  224. if err != nil {
  225. log.Println("易支付回调写入失败")
  226. }
  227. log.Println("易支付回调签名验证失败")
  228. return
  229. }
  230. if verifyInfo.TradeStatus == epay.StatusTradeSuccess {
  231. log.Println(verifyInfo)
  232. LockOrder(verifyInfo.ServiceTradeNo)
  233. defer UnlockOrder(verifyInfo.ServiceTradeNo)
  234. topUp := model.GetTopUpByTradeNo(verifyInfo.ServiceTradeNo)
  235. if topUp == nil {
  236. log.Printf("易支付回调未找到订单: %v", verifyInfo)
  237. return
  238. }
  239. if topUp.Status == "pending" {
  240. topUp.Status = "success"
  241. err := topUp.Update()
  242. if err != nil {
  243. log.Printf("易支付回调更新订单失败: %v", topUp)
  244. return
  245. }
  246. //user, _ := model.GetUserById(topUp.UserId, false)
  247. //user.Quota += topUp.Amount * 500000
  248. dAmount := decimal.NewFromInt(int64(topUp.Amount))
  249. dQuotaPerUnit := decimal.NewFromFloat(common.QuotaPerUnit)
  250. quotaToAdd := int(dAmount.Mul(dQuotaPerUnit).IntPart())
  251. err = model.IncreaseUserQuota(topUp.UserId, quotaToAdd, true)
  252. if err != nil {
  253. log.Printf("易支付回调更新用户失败: %v", topUp)
  254. return
  255. }
  256. log.Printf("易支付回调更新用户成功 %v", topUp)
  257. model.RecordLog(topUp.UserId, model.LogTypeTopup, fmt.Sprintf("使用在线充值成功,充值金额: %v,支付金额:%f", logger.LogQuota(quotaToAdd), topUp.Money))
  258. }
  259. } else {
  260. log.Printf("易支付异常回调: %v", verifyInfo)
  261. }
  262. }
  263. func RequestAmount(c *gin.Context) {
  264. var req AmountRequest
  265. err := c.ShouldBindJSON(&req)
  266. if err != nil {
  267. c.JSON(200, gin.H{"message": "error", "data": "参数错误"})
  268. return
  269. }
  270. if req.Amount < getMinTopup() {
  271. c.JSON(200, gin.H{"message": "error", "data": fmt.Sprintf("充值数量不能小于 %d", getMinTopup())})
  272. return
  273. }
  274. id := c.GetInt("id")
  275. group, err := model.GetUserGroup(id, true)
  276. if err != nil {
  277. c.JSON(200, gin.H{"message": "error", "data": "获取用户分组失败"})
  278. return
  279. }
  280. payMoney := getPayMoney(req.Amount, group)
  281. if payMoney <= 0.01 {
  282. c.JSON(200, gin.H{"message": "error", "data": "充值金额过低"})
  283. return
  284. }
  285. c.JSON(200, gin.H{"message": "success", "data": strconv.FormatFloat(payMoney, 'f', 2, 64)})
  286. }