topup.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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. CreateTime: time.Now().Unix(),
  172. Status: "pending",
  173. }
  174. err = topUp.Insert()
  175. if err != nil {
  176. c.JSON(200, gin.H{"message": "error", "data": "创建订单失败"})
  177. return
  178. }
  179. c.JSON(200, gin.H{"message": "success", "data": params, "url": uri})
  180. }
  181. // tradeNo lock
  182. var orderLocks sync.Map
  183. var createLock sync.Mutex
  184. // LockOrder 尝试对给定订单号加锁
  185. func LockOrder(tradeNo string) {
  186. lock, ok := orderLocks.Load(tradeNo)
  187. if !ok {
  188. createLock.Lock()
  189. defer createLock.Unlock()
  190. lock, ok = orderLocks.Load(tradeNo)
  191. if !ok {
  192. lock = new(sync.Mutex)
  193. orderLocks.Store(tradeNo, lock)
  194. }
  195. }
  196. lock.(*sync.Mutex).Lock()
  197. }
  198. // UnlockOrder 释放给定订单号的锁
  199. func UnlockOrder(tradeNo string) {
  200. lock, ok := orderLocks.Load(tradeNo)
  201. if ok {
  202. lock.(*sync.Mutex).Unlock()
  203. }
  204. }
  205. func EpayNotify(c *gin.Context) {
  206. params := lo.Reduce(lo.Keys(c.Request.URL.Query()), func(r map[string]string, t string, i int) map[string]string {
  207. r[t] = c.Request.URL.Query().Get(t)
  208. return r
  209. }, map[string]string{})
  210. client := GetEpayClient()
  211. if client == nil {
  212. log.Println("易支付回调失败 未找到配置信息")
  213. _, err := c.Writer.Write([]byte("fail"))
  214. if err != nil {
  215. log.Println("易支付回调写入失败")
  216. return
  217. }
  218. }
  219. verifyInfo, err := client.Verify(params)
  220. if err == nil && verifyInfo.VerifyStatus {
  221. _, err := c.Writer.Write([]byte("success"))
  222. if err != nil {
  223. log.Println("易支付回调写入失败")
  224. }
  225. } else {
  226. _, err := c.Writer.Write([]byte("fail"))
  227. if err != nil {
  228. log.Println("易支付回调写入失败")
  229. }
  230. log.Println("易支付回调签名验证失败")
  231. return
  232. }
  233. if verifyInfo.TradeStatus == epay.StatusTradeSuccess {
  234. log.Println(verifyInfo)
  235. LockOrder(verifyInfo.ServiceTradeNo)
  236. defer UnlockOrder(verifyInfo.ServiceTradeNo)
  237. topUp := model.GetTopUpByTradeNo(verifyInfo.ServiceTradeNo)
  238. if topUp == nil {
  239. log.Printf("易支付回调未找到订单: %v", verifyInfo)
  240. return
  241. }
  242. if topUp.Status == "pending" {
  243. topUp.Status = "success"
  244. err := topUp.Update()
  245. if err != nil {
  246. log.Printf("易支付回调更新订单失败: %v", topUp)
  247. return
  248. }
  249. //user, _ := model.GetUserById(topUp.UserId, false)
  250. //user.Quota += topUp.Amount * 500000
  251. dAmount := decimal.NewFromInt(int64(topUp.Amount))
  252. dQuotaPerUnit := decimal.NewFromFloat(common.QuotaPerUnit)
  253. quotaToAdd := int(dAmount.Mul(dQuotaPerUnit).IntPart())
  254. err = model.IncreaseUserQuota(topUp.UserId, quotaToAdd, true)
  255. if err != nil {
  256. log.Printf("易支付回调更新用户失败: %v", topUp)
  257. return
  258. }
  259. log.Printf("易支付回调更新用户成功 %v", topUp)
  260. model.RecordLog(topUp.UserId, model.LogTypeTopup, fmt.Sprintf("使用在线充值成功,充值金额: %v,支付金额:%f", logger.LogQuota(quotaToAdd), topUp.Money))
  261. }
  262. } else {
  263. log.Printf("易支付异常回调: %v", verifyInfo)
  264. }
  265. }
  266. func RequestAmount(c *gin.Context) {
  267. var req AmountRequest
  268. err := c.ShouldBindJSON(&req)
  269. if err != nil {
  270. c.JSON(200, gin.H{"message": "error", "data": "参数错误"})
  271. return
  272. }
  273. if req.Amount < getMinTopup() {
  274. c.JSON(200, gin.H{"message": "error", "data": fmt.Sprintf("充值数量不能小于 %d", getMinTopup())})
  275. return
  276. }
  277. id := c.GetInt("id")
  278. group, err := model.GetUserGroup(id, true)
  279. if err != nil {
  280. c.JSON(200, gin.H{"message": "error", "data": "获取用户分组失败"})
  281. return
  282. }
  283. payMoney := getPayMoney(req.Amount, group)
  284. if payMoney <= 0.01 {
  285. c.JSON(200, gin.H{"message": "error", "data": "充值金额过低"})
  286. return
  287. }
  288. c.JSON(200, gin.H{"message": "success", "data": strconv.FormatFloat(payMoney, 'f', 2, 64)})
  289. }