topup.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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. if !common.DisplayInCurrencyEnabled {
  80. dQuotaPerUnit := decimal.NewFromFloat(common.QuotaPerUnit)
  81. dAmount = dAmount.Div(dQuotaPerUnit)
  82. }
  83. topupGroupRatio := common.GetTopupGroupRatio(group)
  84. if topupGroupRatio == 0 {
  85. topupGroupRatio = 1
  86. }
  87. dTopupGroupRatio := decimal.NewFromFloat(topupGroupRatio)
  88. dPrice := decimal.NewFromFloat(operation_setting.Price)
  89. // apply optional preset discount by the original request amount (if configured), default 1.0
  90. discount := 1.0
  91. if ds, ok := operation_setting.GetPaymentSetting().AmountDiscount[int(amount)]; ok {
  92. if ds > 0 {
  93. discount = ds
  94. }
  95. }
  96. dDiscount := decimal.NewFromFloat(discount)
  97. payMoney := dAmount.Mul(dPrice).Mul(dTopupGroupRatio).Mul(dDiscount)
  98. return payMoney.InexactFloat64()
  99. }
  100. func getMinTopup() int64 {
  101. minTopup := operation_setting.MinTopUp
  102. if !common.DisplayInCurrencyEnabled {
  103. dMinTopup := decimal.NewFromInt(int64(minTopup))
  104. dQuotaPerUnit := decimal.NewFromFloat(common.QuotaPerUnit)
  105. minTopup = int(dMinTopup.Mul(dQuotaPerUnit).IntPart())
  106. }
  107. return int64(minTopup)
  108. }
  109. func RequestEpay(c *gin.Context) {
  110. var req EpayRequest
  111. err := c.ShouldBindJSON(&req)
  112. if err != nil {
  113. c.JSON(200, gin.H{"message": "error", "data": "参数错误"})
  114. return
  115. }
  116. if req.Amount < getMinTopup() {
  117. c.JSON(200, gin.H{"message": "error", "data": fmt.Sprintf("充值数量不能小于 %d", getMinTopup())})
  118. return
  119. }
  120. id := c.GetInt("id")
  121. group, err := model.GetUserGroup(id, true)
  122. if err != nil {
  123. c.JSON(200, gin.H{"message": "error", "data": "获取用户分组失败"})
  124. return
  125. }
  126. payMoney := getPayMoney(req.Amount, group)
  127. if payMoney < 0.01 {
  128. c.JSON(200, gin.H{"message": "error", "data": "充值金额过低"})
  129. return
  130. }
  131. if !operation_setting.ContainsPayMethod(req.PaymentMethod) {
  132. c.JSON(200, gin.H{"message": "error", "data": "支付方式不存在"})
  133. return
  134. }
  135. callBackAddress := service.GetCallbackAddress()
  136. returnUrl, _ := url.Parse(system_setting.ServerAddress + "/console/log")
  137. notifyUrl, _ := url.Parse(callBackAddress + "/api/user/epay/notify")
  138. tradeNo := fmt.Sprintf("%s%d", common.GetRandomString(6), time.Now().Unix())
  139. tradeNo = fmt.Sprintf("USR%dNO%s", id, tradeNo)
  140. client := GetEpayClient()
  141. if client == nil {
  142. c.JSON(200, gin.H{"message": "error", "data": "当前管理员未配置支付信息"})
  143. return
  144. }
  145. uri, params, err := client.Purchase(&epay.PurchaseArgs{
  146. Type: req.PaymentMethod,
  147. ServiceTradeNo: tradeNo,
  148. Name: fmt.Sprintf("TUC%d", req.Amount),
  149. Money: strconv.FormatFloat(payMoney, 'f', 2, 64),
  150. Device: epay.PC,
  151. NotifyUrl: notifyUrl,
  152. ReturnUrl: returnUrl,
  153. })
  154. if err != nil {
  155. c.JSON(200, gin.H{"message": "error", "data": "拉起支付失败"})
  156. return
  157. }
  158. amount := req.Amount
  159. if !common.DisplayInCurrencyEnabled {
  160. dAmount := decimal.NewFromInt(int64(amount))
  161. dQuotaPerUnit := decimal.NewFromFloat(common.QuotaPerUnit)
  162. amount = dAmount.Div(dQuotaPerUnit).IntPart()
  163. }
  164. topUp := &model.TopUp{
  165. UserId: id,
  166. Amount: amount,
  167. Money: payMoney,
  168. TradeNo: tradeNo,
  169. CreateTime: time.Now().Unix(),
  170. Status: "pending",
  171. }
  172. err = topUp.Insert()
  173. if err != nil {
  174. c.JSON(200, gin.H{"message": "error", "data": "创建订单失败"})
  175. return
  176. }
  177. c.JSON(200, gin.H{"message": "success", "data": params, "url": uri})
  178. }
  179. // tradeNo lock
  180. var orderLocks sync.Map
  181. var createLock sync.Mutex
  182. // LockOrder 尝试对给定订单号加锁
  183. func LockOrder(tradeNo string) {
  184. lock, ok := orderLocks.Load(tradeNo)
  185. if !ok {
  186. createLock.Lock()
  187. defer createLock.Unlock()
  188. lock, ok = orderLocks.Load(tradeNo)
  189. if !ok {
  190. lock = new(sync.Mutex)
  191. orderLocks.Store(tradeNo, lock)
  192. }
  193. }
  194. lock.(*sync.Mutex).Lock()
  195. }
  196. // UnlockOrder 释放给定订单号的锁
  197. func UnlockOrder(tradeNo string) {
  198. lock, ok := orderLocks.Load(tradeNo)
  199. if ok {
  200. lock.(*sync.Mutex).Unlock()
  201. }
  202. }
  203. func EpayNotify(c *gin.Context) {
  204. params := lo.Reduce(lo.Keys(c.Request.URL.Query()), func(r map[string]string, t string, i int) map[string]string {
  205. r[t] = c.Request.URL.Query().Get(t)
  206. return r
  207. }, map[string]string{})
  208. client := GetEpayClient()
  209. if client == nil {
  210. log.Println("易支付回调失败 未找到配置信息")
  211. _, err := c.Writer.Write([]byte("fail"))
  212. if err != nil {
  213. log.Println("易支付回调写入失败")
  214. return
  215. }
  216. }
  217. verifyInfo, err := client.Verify(params)
  218. if err == nil && verifyInfo.VerifyStatus {
  219. _, err := c.Writer.Write([]byte("success"))
  220. if err != nil {
  221. log.Println("易支付回调写入失败")
  222. }
  223. } else {
  224. _, err := c.Writer.Write([]byte("fail"))
  225. if err != nil {
  226. log.Println("易支付回调写入失败")
  227. }
  228. log.Println("易支付回调签名验证失败")
  229. return
  230. }
  231. if verifyInfo.TradeStatus == epay.StatusTradeSuccess {
  232. log.Println(verifyInfo)
  233. LockOrder(verifyInfo.ServiceTradeNo)
  234. defer UnlockOrder(verifyInfo.ServiceTradeNo)
  235. topUp := model.GetTopUpByTradeNo(verifyInfo.ServiceTradeNo)
  236. if topUp == nil {
  237. log.Printf("易支付回调未找到订单: %v", verifyInfo)
  238. return
  239. }
  240. if topUp.Status == "pending" {
  241. topUp.Status = "success"
  242. err := topUp.Update()
  243. if err != nil {
  244. log.Printf("易支付回调更新订单失败: %v", topUp)
  245. return
  246. }
  247. //user, _ := model.GetUserById(topUp.UserId, false)
  248. //user.Quota += topUp.Amount * 500000
  249. dAmount := decimal.NewFromInt(int64(topUp.Amount))
  250. dQuotaPerUnit := decimal.NewFromFloat(common.QuotaPerUnit)
  251. quotaToAdd := int(dAmount.Mul(dQuotaPerUnit).IntPart())
  252. err = model.IncreaseUserQuota(topUp.UserId, quotaToAdd, true)
  253. if err != nil {
  254. log.Printf("易支付回调更新用户失败: %v", topUp)
  255. return
  256. }
  257. log.Printf("易支付回调更新用户成功 %v", topUp)
  258. model.RecordLog(topUp.UserId, model.LogTypeTopup, fmt.Sprintf("使用在线充值成功,充值金额: %v,支付金额:%f", logger.LogQuota(quotaToAdd), topUp.Money))
  259. }
  260. } else {
  261. log.Printf("易支付异常回调: %v", verifyInfo)
  262. }
  263. }
  264. func RequestAmount(c *gin.Context) {
  265. var req AmountRequest
  266. err := c.ShouldBindJSON(&req)
  267. if err != nil {
  268. c.JSON(200, gin.H{"message": "error", "data": "参数错误"})
  269. return
  270. }
  271. if req.Amount < getMinTopup() {
  272. c.JSON(200, gin.H{"message": "error", "data": fmt.Sprintf("充值数量不能小于 %d", getMinTopup())})
  273. return
  274. }
  275. id := c.GetInt("id")
  276. group, err := model.GetUserGroup(id, true)
  277. if err != nil {
  278. c.JSON(200, gin.H{"message": "error", "data": "获取用户分组失败"})
  279. return
  280. }
  281. payMoney := getPayMoney(req.Amount, group)
  282. if payMoney <= 0.01 {
  283. c.JSON(200, gin.H{"message": "error", "data": "充值金额过低"})
  284. return
  285. }
  286. c.JSON(200, gin.H{"message": "success", "data": strconv.FormatFloat(payMoney, 'f', 2, 64)})
  287. }