topup.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  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. var payType epay.PurchaseType
  60. if req.PaymentMethod == "zfb" {
  61. payType = epay.Alipay
  62. }
  63. if req.PaymentMethod == "wx" {
  64. req.PaymentMethod = "wxpay"
  65. payType = epay.WechatPay
  66. }
  67. returnUrl, _ := url.Parse(common.ServerAddress + "/log")
  68. notifyUrl, _ := url.Parse(common.ServerAddress + "/api/user/epay/notify")
  69. tradeNo := strconv.FormatInt(time.Now().Unix(), 10)
  70. payMoney := amount
  71. client := GetEpayClient()
  72. if client == nil {
  73. c.JSON(200, gin.H{"message": "error", "data": "当前管理员未配置支付信息"})
  74. return
  75. }
  76. uri, params, err := client.Purchase(&epay.PurchaseArgs{
  77. Type: payType,
  78. ServiceTradeNo: "A" + tradeNo,
  79. Name: "B" + tradeNo,
  80. Money: strconv.FormatFloat(payMoney, 'f', 2, 64),
  81. Device: epay.PC,
  82. NotifyUrl: notifyUrl,
  83. ReturnUrl: returnUrl,
  84. })
  85. if err != nil {
  86. c.JSON(200, gin.H{"message": "error", "data": "拉起支付失败"})
  87. return
  88. }
  89. topUp := &model.TopUp{
  90. UserId: id,
  91. Amount: req.Amount,
  92. Money: payMoney,
  93. TradeNo: "A" + tradeNo,
  94. CreateTime: time.Now().Unix(),
  95. Status: "pending",
  96. }
  97. err = topUp.Insert()
  98. if err != nil {
  99. c.JSON(200, gin.H{"message": "error", "data": "创建订单失败"})
  100. return
  101. }
  102. c.JSON(200, gin.H{"message": "success", "data": params, "url": uri})
  103. }
  104. func EpayNotify(c *gin.Context) {
  105. params := lo.Reduce(lo.Keys(c.Request.URL.Query()), func(r map[string]string, t string, i int) map[string]string {
  106. r[t] = c.Request.URL.Query().Get(t)
  107. return r
  108. }, map[string]string{})
  109. client := GetEpayClient()
  110. if client == nil {
  111. log.Println("易支付回调失败 未找到配置信息")
  112. _, err := c.Writer.Write([]byte("fail"))
  113. if err != nil {
  114. log.Println("易支付回调写入失败")
  115. }
  116. }
  117. verifyInfo, err := client.Verify(params)
  118. if err == nil && verifyInfo.VerifyStatus {
  119. _, err := c.Writer.Write([]byte("success"))
  120. if err != nil {
  121. log.Println("易支付回调写入失败")
  122. }
  123. } else {
  124. _, err := c.Writer.Write([]byte("fail"))
  125. if err != nil {
  126. log.Println("易支付回调写入失败")
  127. }
  128. }
  129. if verifyInfo.TradeStatus == epay.StatusTradeSuccess {
  130. log.Println(verifyInfo)
  131. topUp := model.GetTopUpByTradeNo(verifyInfo.ServiceTradeNo)
  132. if topUp.Status == "pending" {
  133. topUp.Status = "success"
  134. err := topUp.Update()
  135. if err != nil {
  136. log.Printf("易支付回调更新订单失败: %v", topUp)
  137. return
  138. }
  139. //user, _ := model.GetUserById(topUp.UserId, false)
  140. //user.Quota += topUp.Amount * 500000
  141. err = model.IncreaseUserQuota(topUp.UserId, topUp.Amount*500000)
  142. if err != nil {
  143. log.Printf("易支付回调更新用户失败: %v", topUp)
  144. return
  145. }
  146. log.Printf("易支付回调更新用户成功 %v", topUp)
  147. model.RecordLog(topUp.UserId, model.LogTypeTopup, fmt.Sprintf("使用在线充值成功,充值金额: %v,支付金额:%f", common.LogQuota(topUp.Amount*500000), topUp.Money))
  148. }
  149. } else {
  150. log.Printf("易支付异常回调: %v", verifyInfo)
  151. }
  152. }
  153. func RequestAmount(c *gin.Context) {
  154. var req AmountRequest
  155. err := c.ShouldBindJSON(&req)
  156. if err != nil {
  157. c.JSON(200, gin.H{"message": "error", "data": "参数错误"})
  158. return
  159. }
  160. if req.Amount < 1 {
  161. c.JSON(200, gin.H{"message": "error", "data": "充值金额不能小于1"})
  162. return
  163. }
  164. id := c.GetInt("id")
  165. user, _ := model.GetUserById(id, false)
  166. payMoney := GetAmount(float64(req.Amount), *user)
  167. c.JSON(200, gin.H{"message": "success", "data": strconv.FormatFloat(payMoney, 'f', 2, 64)})
  168. }