topup.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. package controller
  2. import (
  3. "fmt"
  4. "github.com/gin-gonic/gin"
  5. "github.com/samber/lo"
  6. epay "github.com/star-horizon/go-epay"
  7. "log"
  8. "net/url"
  9. "one-api/common"
  10. "one-api/model"
  11. "strconv"
  12. "time"
  13. )
  14. type EpayRequest struct {
  15. Amount int `json:"amount"`
  16. PaymentMethod string `json:"payment_method"`
  17. TopUpCode string `json:"top_up_code"`
  18. }
  19. type AmountRequest struct {
  20. Amount int `json:"amount"`
  21. TopUpCode string `json:"top_up_code"`
  22. }
  23. func GetEpayClient() *epay.Client {
  24. if common.PayAddress == "" || common.EpayId == "" || common.EpayKey == "" {
  25. return nil
  26. }
  27. withUrl, err := epay.NewClientWithUrl(&epay.Config{
  28. PartnerID: common.EpayId,
  29. Key: common.EpayKey,
  30. }, common.PayAddress)
  31. if err != nil {
  32. return nil
  33. }
  34. return withUrl
  35. }
  36. func GetAmount(count float64, user model.User) float64 {
  37. // 别问为什么用float64,问就是这么点钱没必要
  38. topupGroupRatio := common.GetTopupGroupRatio(user.Group)
  39. if topupGroupRatio == 0 {
  40. topupGroupRatio = 1
  41. }
  42. amount := count * common.Price * topupGroupRatio
  43. return amount
  44. }
  45. func RequestEpay(c *gin.Context) {
  46. var req EpayRequest
  47. err := c.ShouldBindJSON(&req)
  48. if err != nil {
  49. c.JSON(200, gin.H{"message": err.Error(), "data": 10})
  50. return
  51. }
  52. if req.Amount < 1 {
  53. c.JSON(200, gin.H{"message": "充值金额不能小于1", "data": 10})
  54. return
  55. }
  56. id := c.GetInt("id")
  57. user, _ := model.GetUserById(id, false)
  58. amount := GetAmount(float64(req.Amount), *user)
  59. if req.PaymentMethod == "zfb" {
  60. req.PaymentMethod = "alipay"
  61. }
  62. if req.PaymentMethod == "wx" {
  63. req.PaymentMethod = "wxpay"
  64. }
  65. returnUrl, _ := url.Parse(common.ServerAddress + "/log")
  66. notifyUrl, _ := url.Parse(common.ServerAddress + "/api/user/epay/notify")
  67. tradeNo := strconv.FormatInt(time.Now().Unix(), 10)
  68. payMoney := amount
  69. client := GetEpayClient()
  70. if client == nil {
  71. c.JSON(200, gin.H{"message": "error", "data": "当前管理员未配置支付信息"})
  72. return
  73. }
  74. uri, params, err := client.Purchase(&epay.PurchaseArgs{
  75. Type: epay.PurchaseType(req.PaymentMethod),
  76. ServiceTradeNo: "A" + tradeNo,
  77. Name: "B" + tradeNo,
  78. Money: strconv.FormatFloat(payMoney, 'f', 2, 64),
  79. Device: epay.PC,
  80. NotifyUrl: notifyUrl,
  81. ReturnUrl: returnUrl,
  82. })
  83. if err != nil {
  84. c.JSON(200, gin.H{"message": "error", "data": "拉起支付失败"})
  85. return
  86. }
  87. topUp := &model.TopUp{
  88. UserId: id,
  89. Amount: req.Amount,
  90. Money: int(amount),
  91. TradeNo: "A" + tradeNo,
  92. CreateTime: time.Now().Unix(),
  93. Status: "pending",
  94. }
  95. err = topUp.Insert()
  96. if err != nil {
  97. c.JSON(200, gin.H{"message": "error", "data": "创建订单失败"})
  98. return
  99. }
  100. c.JSON(200, gin.H{"message": "success", "data": params, "url": uri})
  101. }
  102. func EpayNotify(c *gin.Context) {
  103. params := lo.Reduce(lo.Keys(c.Request.URL.Query()), func(r map[string]string, t string, i int) map[string]string {
  104. r[t] = c.Request.URL.Query().Get(t)
  105. return r
  106. }, map[string]string{})
  107. client := GetEpayClient()
  108. if client == nil {
  109. log.Println("易支付回调失败 未找到配置信息")
  110. _, err := c.Writer.Write([]byte("fail"))
  111. if err != nil {
  112. log.Println("易支付回调写入失败")
  113. }
  114. }
  115. verifyInfo, err := client.Verify(params)
  116. if err == nil && verifyInfo.VerifyStatus {
  117. _, err := c.Writer.Write([]byte("success"))
  118. if err != nil {
  119. log.Println("易支付回调写入失败")
  120. }
  121. } else {
  122. _, err := c.Writer.Write([]byte("fail"))
  123. if err != nil {
  124. log.Println("易支付回调写入失败")
  125. }
  126. }
  127. if verifyInfo.TradeStatus == epay.StatusTradeSuccess {
  128. log.Println(verifyInfo)
  129. topUp := model.GetTopUpByTradeNo(verifyInfo.ServiceTradeNo)
  130. if topUp.Status == "pending" {
  131. topUp.Status = "success"
  132. err := topUp.Update()
  133. if err != nil {
  134. log.Printf("易支付回调更新订单失败: %v", topUp)
  135. return
  136. }
  137. //user, _ := model.GetUserById(topUp.UserId, false)
  138. //user.Quota += topUp.Amount * 500000
  139. err = model.IncreaseUserQuota(topUp.UserId, topUp.Amount*500000)
  140. if err != nil {
  141. log.Printf("易支付回调更新用户失败: %v", topUp)
  142. return
  143. }
  144. log.Printf("易支付回调更新用户成功 %v", topUp)
  145. model.RecordLog(topUp.UserId, model.LogTypeTopup, fmt.Sprintf("使用在线充值成功,充值金额: %v,支付金额:%d", common.LogQuota(topUp.Amount*500000), topUp.Money))
  146. }
  147. } else {
  148. log.Printf("易支付异常回调: %v", verifyInfo)
  149. }
  150. }
  151. func RequestAmount(c *gin.Context) {
  152. var req AmountRequest
  153. err := c.ShouldBindJSON(&req)
  154. if err != nil {
  155. c.JSON(200, gin.H{"message": "error", "data": "参数错误"})
  156. return
  157. }
  158. if req.Amount < 1 {
  159. c.JSON(200, gin.H{"message": "error", "data": "充值金额不能小于1"})
  160. return
  161. }
  162. id := c.GetInt("id")
  163. user, _ := model.GetUserById(id, false)
  164. c.JSON(200, gin.H{"message": "success", "data": GetAmount(float64(req.Amount), *user)})
  165. }