topup.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. package controller
  2. import (
  3. "fmt"
  4. "github.com/Calcium-Ion/go-epay/epay"
  5. "github.com/gin-gonic/gin"
  6. "github.com/samber/lo"
  7. "log"
  8. "net/url"
  9. "one-api/common"
  10. "one-api/model"
  11. "one-api/service"
  12. "one-api/setting"
  13. "strconv"
  14. "sync"
  15. "time"
  16. )
  17. type EpayRequest struct {
  18. Amount int `json:"amount"`
  19. PaymentMethod string `json:"payment_method"`
  20. TopUpCode string `json:"top_up_code"`
  21. }
  22. type AmountRequest struct {
  23. Amount int `json:"amount"`
  24. TopUpCode string `json:"top_up_code"`
  25. }
  26. func GetEpayClient() *epay.Client {
  27. if setting.PayAddress == "" || setting.EpayId == "" || setting.EpayKey == "" {
  28. return nil
  29. }
  30. withUrl, err := epay.NewClient(&epay.Config{
  31. PartnerID: setting.EpayId,
  32. Key: setting.EpayKey,
  33. }, setting.PayAddress)
  34. if err != nil {
  35. return nil
  36. }
  37. return withUrl
  38. }
  39. func getPayMoney(amount float64, group string) float64 {
  40. if !common.DisplayInCurrencyEnabled {
  41. amount = amount / common.QuotaPerUnit
  42. }
  43. // 别问为什么用float64,问就是这么点钱没必要
  44. topupGroupRatio := common.GetTopupGroupRatio(group)
  45. if topupGroupRatio == 0 {
  46. topupGroupRatio = 1
  47. }
  48. payMoney := amount * setting.Price * topupGroupRatio
  49. return payMoney
  50. }
  51. func getMinTopup() int {
  52. minTopup := setting.MinTopUp
  53. if !common.DisplayInCurrencyEnabled {
  54. minTopup = minTopup * int(common.QuotaPerUnit)
  55. }
  56. return minTopup
  57. }
  58. func RequestEpay(c *gin.Context) {
  59. var req EpayRequest
  60. err := c.ShouldBindJSON(&req)
  61. if err != nil {
  62. c.JSON(200, gin.H{"message": "error", "data": "参数错误"})
  63. return
  64. }
  65. if req.Amount < getMinTopup() {
  66. c.JSON(200, gin.H{"message": "error", "data": fmt.Sprintf("充值数量不能小于 %d", getMinTopup())})
  67. return
  68. }
  69. id := c.GetInt("id")
  70. group, err := model.GetUserGroup(id, true)
  71. if err != nil {
  72. c.JSON(200, gin.H{"message": "error", "data": "获取用户分组失败"})
  73. return
  74. }
  75. payMoney := getPayMoney(float64(req.Amount), group)
  76. if payMoney < 0.01 {
  77. c.JSON(200, gin.H{"message": "error", "data": "充值金额过低"})
  78. return
  79. }
  80. payType := "wxpay"
  81. if req.PaymentMethod == "zfb" {
  82. payType = "alipay"
  83. }
  84. if req.PaymentMethod == "wx" {
  85. req.PaymentMethod = "wxpay"
  86. payType = "wxpay"
  87. }
  88. callBackAddress := service.GetCallbackAddress()
  89. returnUrl, _ := url.Parse(setting.ServerAddress + "/log")
  90. notifyUrl, _ := url.Parse(callBackAddress + "/api/user/epay/notify")
  91. tradeNo := fmt.Sprintf("%s%d", common.GetRandomString(6), time.Now().Unix())
  92. tradeNo = fmt.Sprintf("USR%dNO%s", id, tradeNo)
  93. client := GetEpayClient()
  94. if client == nil {
  95. c.JSON(200, gin.H{"message": "error", "data": "当前管理员未配置支付信息"})
  96. return
  97. }
  98. uri, params, err := client.Purchase(&epay.PurchaseArgs{
  99. Type: payType,
  100. ServiceTradeNo: tradeNo,
  101. Name: fmt.Sprintf("TUC%d", req.Amount),
  102. Money: strconv.FormatFloat(payMoney, 'f', 2, 64),
  103. Device: epay.PC,
  104. NotifyUrl: notifyUrl,
  105. ReturnUrl: returnUrl,
  106. })
  107. if err != nil {
  108. c.JSON(200, gin.H{"message": "error", "data": "拉起支付失败"})
  109. return
  110. }
  111. amount := req.Amount
  112. if !common.DisplayInCurrencyEnabled {
  113. amount = amount / int(common.QuotaPerUnit)
  114. }
  115. topUp := &model.TopUp{
  116. UserId: id,
  117. Amount: amount,
  118. Money: payMoney,
  119. TradeNo: tradeNo,
  120. CreateTime: time.Now().Unix(),
  121. Status: "pending",
  122. }
  123. err = topUp.Insert()
  124. if err != nil {
  125. c.JSON(200, gin.H{"message": "error", "data": "创建订单失败"})
  126. return
  127. }
  128. c.JSON(200, gin.H{"message": "success", "data": params, "url": uri})
  129. }
  130. // tradeNo lock
  131. var orderLocks sync.Map
  132. var createLock sync.Mutex
  133. // LockOrder 尝试对给定订单号加锁
  134. func LockOrder(tradeNo string) {
  135. lock, ok := orderLocks.Load(tradeNo)
  136. if !ok {
  137. createLock.Lock()
  138. defer createLock.Unlock()
  139. lock, ok = orderLocks.Load(tradeNo)
  140. if !ok {
  141. lock = new(sync.Mutex)
  142. orderLocks.Store(tradeNo, lock)
  143. }
  144. }
  145. lock.(*sync.Mutex).Lock()
  146. }
  147. // UnlockOrder 释放给定订单号的锁
  148. func UnlockOrder(tradeNo string) {
  149. lock, ok := orderLocks.Load(tradeNo)
  150. if ok {
  151. lock.(*sync.Mutex).Unlock()
  152. }
  153. }
  154. func EpayNotify(c *gin.Context) {
  155. params := lo.Reduce(lo.Keys(c.Request.URL.Query()), func(r map[string]string, t string, i int) map[string]string {
  156. r[t] = c.Request.URL.Query().Get(t)
  157. return r
  158. }, map[string]string{})
  159. client := GetEpayClient()
  160. if client == nil {
  161. log.Println("易支付回调失败 未找到配置信息")
  162. _, err := c.Writer.Write([]byte("fail"))
  163. if err != nil {
  164. log.Println("易支付回调写入失败")
  165. return
  166. }
  167. }
  168. verifyInfo, err := client.Verify(params)
  169. if err == nil && verifyInfo.VerifyStatus {
  170. _, err := c.Writer.Write([]byte("success"))
  171. if err != nil {
  172. log.Println("易支付回调写入失败")
  173. }
  174. } else {
  175. _, err := c.Writer.Write([]byte("fail"))
  176. if err != nil {
  177. log.Println("易支付回调写入失败")
  178. }
  179. log.Println("易支付回调签名验证失败")
  180. return
  181. }
  182. if verifyInfo.TradeStatus == epay.StatusTradeSuccess {
  183. log.Println(verifyInfo)
  184. LockOrder(verifyInfo.ServiceTradeNo)
  185. defer UnlockOrder(verifyInfo.ServiceTradeNo)
  186. topUp := model.GetTopUpByTradeNo(verifyInfo.ServiceTradeNo)
  187. if topUp == nil {
  188. log.Printf("易支付回调未找到订单: %v", verifyInfo)
  189. return
  190. }
  191. if topUp.Status == "pending" {
  192. topUp.Status = "success"
  193. err := topUp.Update()
  194. if err != nil {
  195. log.Printf("易支付回调更新订单失败: %v", topUp)
  196. return
  197. }
  198. //user, _ := model.GetUserById(topUp.UserId, false)
  199. //user.Quota += topUp.Amount * 500000
  200. err = model.IncreaseUserQuota(topUp.UserId, topUp.Amount*int(common.QuotaPerUnit))
  201. if err != nil {
  202. log.Printf("易支付回调更新用户失败: %v", topUp)
  203. return
  204. }
  205. log.Printf("易支付回调更新用户成功 %v", topUp)
  206. model.RecordLog(topUp.UserId, model.LogTypeTopup, fmt.Sprintf("使用在线充值成功,充值金额: %v,支付金额:%f", common.LogQuota(topUp.Amount*int(common.QuotaPerUnit)), topUp.Money))
  207. }
  208. } else {
  209. log.Printf("易支付异常回调: %v", verifyInfo)
  210. }
  211. }
  212. func RequestAmount(c *gin.Context) {
  213. var req AmountRequest
  214. err := c.ShouldBindJSON(&req)
  215. if err != nil {
  216. c.JSON(200, gin.H{"message": "error", "data": "参数错误"})
  217. return
  218. }
  219. if req.Amount < getMinTopup() {
  220. c.JSON(200, gin.H{"message": "error", "data": fmt.Sprintf("充值数量不能小于 %d", getMinTopup())})
  221. return
  222. }
  223. id := c.GetInt("id")
  224. group, err := model.GetUserGroup(id, true)
  225. if err != nil {
  226. c.JSON(200, gin.H{"message": "error", "data": "获取用户分组失败"})
  227. return
  228. }
  229. payMoney := getPayMoney(float64(req.Amount), group)
  230. if payMoney <= 0.01 {
  231. c.JSON(200, gin.H{"message": "error", "data": "充值金额过低"})
  232. return
  233. }
  234. c.JSON(200, gin.H{"message": "success", "data": strconv.FormatFloat(payMoney, 'f', 2, 64)})
  235. }