Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 

461 řádky
13 KiB

  1. package controller
  2. import (
  3. "fmt"
  4. "log"
  5. "net/url"
  6. "strconv"
  7. "sync"
  8. "time"
  9. "github.com/QuantumNous/new-api/common"
  10. "github.com/QuantumNous/new-api/logger"
  11. "github.com/QuantumNous/new-api/model"
  12. "github.com/QuantumNous/new-api/service"
  13. "github.com/QuantumNous/new-api/setting"
  14. "github.com/QuantumNous/new-api/setting/operation_setting"
  15. "github.com/QuantumNous/new-api/setting/system_setting"
  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. enableOnlineTopup := operation_setting.PayAddress != "" && operation_setting.EpayId != "" && operation_setting.EpayKey != ""
  23. // 获取支付方式:易支付未启用时过滤掉旧支付方法
  24. payMethods := operation_setting.PayMethods
  25. if !enableOnlineTopup {
  26. payMethods = []map[string]string{}
  27. }
  28. // 如果启用了 Stripe 支付,添加到支付方法列表
  29. if setting.StripeApiSecret != "" && setting.StripeWebhookSecret != "" && setting.StripePriceId != "" {
  30. // 检查是否已经包含 Stripe
  31. hasStripe := false
  32. for _, method := range payMethods {
  33. if method["type"] == "stripe" {
  34. hasStripe = true
  35. break
  36. }
  37. }
  38. if !hasStripe {
  39. stripeMethod := map[string]string{
  40. "name": "Stripe",
  41. "type": "stripe",
  42. "color": "rgba(var(--semi-purple-5), 1)",
  43. "min_topup": strconv.Itoa(setting.StripeMinTopUp),
  44. }
  45. payMethods = append(payMethods, stripeMethod)
  46. }
  47. }
  48. // 如果启用了微信支付,添加到支付方法列表
  49. if setting.IsWechatPayConfigured() {
  50. hasWechat := false
  51. for _, method := range payMethods {
  52. if method["type"] == PaymentMethodWechatPay {
  53. hasWechat = true
  54. break
  55. }
  56. }
  57. if !hasWechat {
  58. wechatMethod := map[string]string{
  59. "name": "WeChat Pay",
  60. "type": PaymentMethodWechatPay,
  61. "color": "rgba(var(--semi-green-5), 1)",
  62. "min_topup": strconv.Itoa(setting.WechatPayMinTopUp),
  63. }
  64. payMethods = append(payMethods, wechatMethod)
  65. }
  66. }
  67. // 如果启用了支付宝支付,添加到支付方法列表
  68. if setting.IsAlipayConfigured() {
  69. hasAlipay := false
  70. for _, method := range payMethods {
  71. if method["type"] == PaymentMethodAlipay {
  72. hasAlipay = true
  73. break
  74. }
  75. }
  76. if !hasAlipay {
  77. alipayMethod := map[string]string{
  78. "name": "Alipay",
  79. "type": PaymentMethodAlipay,
  80. "color": "rgba(var(--semi-blue-5), 1)",
  81. "min_topup": strconv.Itoa(setting.AlipayMinTopUp),
  82. }
  83. payMethods = append(payMethods, alipayMethod)
  84. }
  85. }
  86. data := gin.H{
  87. "enable_online_topup": enableOnlineTopup,
  88. "enable_stripe_topup": setting.StripeApiSecret != "" && setting.StripeWebhookSecret != "" && setting.StripePriceId != "",
  89. "enable_creem_topup": setting.CreemApiKey != "" && setting.CreemProducts != "[]",
  90. "enable_wechat_topup": setting.IsWechatPayConfigured(),
  91. "enable_alipay_topup": setting.IsAlipayConfigured(),
  92. "creem_products": setting.CreemProducts,
  93. "pay_methods": payMethods,
  94. "min_topup": operation_setting.MinTopUp,
  95. "stripe_min_topup": setting.StripeMinTopUp,
  96. "wechat_pay_min_topup": setting.WechatPayMinTopUp,
  97. "alipay_pay_min_topup": setting.AlipayMinTopUp,
  98. "amount_options": operation_setting.GetPaymentSetting().AmountOptions,
  99. "discount": operation_setting.GetPaymentSetting().AmountDiscount,
  100. }
  101. common.ApiSuccess(c, data)
  102. }
  103. type EpayRequest struct {
  104. Amount int64 `json:"amount"`
  105. PaymentMethod string `json:"payment_method"`
  106. }
  107. type AmountRequest struct {
  108. Amount int64 `json:"amount"`
  109. }
  110. func GetEpayClient() *epay.Client {
  111. if operation_setting.PayAddress == "" || operation_setting.EpayId == "" || operation_setting.EpayKey == "" {
  112. return nil
  113. }
  114. withUrl, err := epay.NewClient(&epay.Config{
  115. PartnerID: operation_setting.EpayId,
  116. Key: operation_setting.EpayKey,
  117. }, operation_setting.PayAddress)
  118. if err != nil {
  119. return nil
  120. }
  121. return withUrl
  122. }
  123. func getPayMoney(amount int64, group string) float64 {
  124. dAmount := decimal.NewFromInt(amount)
  125. // 充值金额以“展示类型”为准:
  126. // - USD/CNY: 前端传 amount 为金额单位;TOKENS: 前端传 tokens,需要换成 USD 金额
  127. if operation_setting.GetQuotaDisplayType() == operation_setting.QuotaDisplayTypeTokens {
  128. dQuotaPerUnit := decimal.NewFromFloat(common.QuotaPerUnit)
  129. dAmount = dAmount.Div(dQuotaPerUnit)
  130. }
  131. topupGroupRatio := common.GetTopupGroupRatio(group)
  132. if topupGroupRatio == 0 {
  133. topupGroupRatio = 1
  134. }
  135. dTopupGroupRatio := decimal.NewFromFloat(topupGroupRatio)
  136. dPrice := decimal.NewFromFloat(operation_setting.Price)
  137. // apply optional preset discount by the original request amount (if configured), default 1.0
  138. discount := 1.0
  139. if ds, ok := operation_setting.GetPaymentSetting().AmountDiscount[int(amount)]; ok {
  140. if ds > 0 {
  141. discount = ds
  142. }
  143. }
  144. dDiscount := decimal.NewFromFloat(discount)
  145. payMoney := dAmount.Mul(dPrice).Mul(dTopupGroupRatio).Mul(dDiscount)
  146. return payMoney.InexactFloat64()
  147. }
  148. func getMinTopup() int64 {
  149. minTopup := operation_setting.MinTopUp
  150. if operation_setting.GetQuotaDisplayType() == operation_setting.QuotaDisplayTypeTokens {
  151. dMinTopup := decimal.NewFromInt(int64(minTopup))
  152. dQuotaPerUnit := decimal.NewFromFloat(common.QuotaPerUnit)
  153. minTopup = int(dMinTopup.Mul(dQuotaPerUnit).IntPart())
  154. }
  155. return int64(minTopup)
  156. }
  157. func RequestEpay(c *gin.Context) {
  158. var req EpayRequest
  159. err := c.ShouldBindJSON(&req)
  160. if err != nil {
  161. c.JSON(200, gin.H{"message": "error", "data": "参数错误"})
  162. return
  163. }
  164. if req.Amount < getMinTopup() {
  165. c.JSON(200, gin.H{"message": "error", "data": fmt.Sprintf("充值数量不能小于 %d", getMinTopup())})
  166. return
  167. }
  168. id := c.GetInt("id")
  169. group, err := model.GetUserGroup(id, true)
  170. if err != nil {
  171. c.JSON(200, gin.H{"message": "error", "data": "获取用户分组失败"})
  172. return
  173. }
  174. payMoney := getPayMoney(req.Amount, group)
  175. if payMoney < 0.01 {
  176. c.JSON(200, gin.H{"message": "error", "data": "充值金额过低"})
  177. return
  178. }
  179. if !operation_setting.ContainsPayMethod(req.PaymentMethod) {
  180. c.JSON(200, gin.H{"message": "error", "data": "支付方式不存在"})
  181. return
  182. }
  183. callBackAddress := service.GetCallbackAddress()
  184. returnUrl, _ := url.Parse(system_setting.ServerAddress + "/console/log")
  185. notifyUrl, _ := url.Parse(callBackAddress + "/api/user/epay/notify")
  186. tradeNo := fmt.Sprintf("%s%d", common.GetRandomString(6), time.Now().Unix())
  187. tradeNo = fmt.Sprintf("USR%dNO%s", id, tradeNo)
  188. client := GetEpayClient()
  189. if client == nil {
  190. c.JSON(200, gin.H{"message": "error", "data": "当前管理员未配置支付信息"})
  191. return
  192. }
  193. uri, params, err := client.Purchase(&epay.PurchaseArgs{
  194. Type: req.PaymentMethod,
  195. ServiceTradeNo: tradeNo,
  196. Name: fmt.Sprintf("TUC%d", req.Amount),
  197. Money: strconv.FormatFloat(payMoney, 'f', 2, 64),
  198. Device: epay.PC,
  199. NotifyUrl: notifyUrl,
  200. ReturnUrl: returnUrl,
  201. })
  202. if err != nil {
  203. c.JSON(200, gin.H{"message": "error", "data": "拉起支付失败"})
  204. return
  205. }
  206. amount := req.Amount
  207. if operation_setting.GetQuotaDisplayType() == operation_setting.QuotaDisplayTypeTokens {
  208. dAmount := decimal.NewFromInt(int64(amount))
  209. dQuotaPerUnit := decimal.NewFromFloat(common.QuotaPerUnit)
  210. amount = dAmount.Div(dQuotaPerUnit).IntPart()
  211. }
  212. topUp := &model.TopUp{
  213. UserId: id,
  214. Amount: amount,
  215. Money: payMoney,
  216. TradeNo: tradeNo,
  217. PaymentMethod: req.PaymentMethod,
  218. CreateTime: time.Now().Unix(),
  219. Status: "pending",
  220. }
  221. err = topUp.Insert()
  222. if err != nil {
  223. c.JSON(200, gin.H{"message": "error", "data": "创建订单失败"})
  224. return
  225. }
  226. c.JSON(200, gin.H{"message": "success", "data": params, "url": uri})
  227. }
  228. // tradeNo lock
  229. var orderLocks sync.Map
  230. var createLock sync.Mutex
  231. // LockOrder 尝试对给定订单号加锁
  232. func LockOrder(tradeNo string) {
  233. lock, ok := orderLocks.Load(tradeNo)
  234. if !ok {
  235. createLock.Lock()
  236. defer createLock.Unlock()
  237. lock, ok = orderLocks.Load(tradeNo)
  238. if !ok {
  239. lock = new(sync.Mutex)
  240. orderLocks.Store(tradeNo, lock)
  241. }
  242. }
  243. lock.(*sync.Mutex).Lock()
  244. }
  245. // UnlockOrder 释放给定订单号的锁
  246. func UnlockOrder(tradeNo string) {
  247. lock, ok := orderLocks.Load(tradeNo)
  248. if ok {
  249. lock.(*sync.Mutex).Unlock()
  250. }
  251. }
  252. func EpayNotify(c *gin.Context) {
  253. var params map[string]string
  254. if c.Request.Method == "POST" {
  255. // POST 请求:从 POST body 解析参数
  256. if err := c.Request.ParseForm(); err != nil {
  257. log.Println("易支付回调POST解析失败:", err)
  258. _, _ = c.Writer.Write([]byte("fail"))
  259. return
  260. }
  261. params = lo.Reduce(lo.Keys(c.Request.PostForm), func(r map[string]string, t string, i int) map[string]string {
  262. r[t] = c.Request.PostForm.Get(t)
  263. return r
  264. }, map[string]string{})
  265. } else {
  266. // GET 请求:从 URL Query 解析参数
  267. params = lo.Reduce(lo.Keys(c.Request.URL.Query()), func(r map[string]string, t string, i int) map[string]string {
  268. r[t] = c.Request.URL.Query().Get(t)
  269. return r
  270. }, map[string]string{})
  271. }
  272. if len(params) == 0 {
  273. log.Println("易支付回调参数为空")
  274. _, _ = c.Writer.Write([]byte("fail"))
  275. return
  276. }
  277. client := GetEpayClient()
  278. if client == nil {
  279. log.Println("易支付回调失败 未找到配置信息")
  280. _, err := c.Writer.Write([]byte("fail"))
  281. if err != nil {
  282. log.Println("易支付回调写入失败")
  283. }
  284. return
  285. }
  286. verifyInfo, err := client.Verify(params)
  287. if err == nil && verifyInfo.VerifyStatus {
  288. _, err := c.Writer.Write([]byte("success"))
  289. if err != nil {
  290. log.Println("易支付回调写入失败")
  291. }
  292. } else {
  293. _, err := c.Writer.Write([]byte("fail"))
  294. if err != nil {
  295. log.Println("易支付回调写入失败")
  296. }
  297. log.Println("易支付回调签名验证失败")
  298. return
  299. }
  300. if verifyInfo.TradeStatus == epay.StatusTradeSuccess {
  301. log.Println(verifyInfo)
  302. LockOrder(verifyInfo.ServiceTradeNo)
  303. defer UnlockOrder(verifyInfo.ServiceTradeNo)
  304. topUp := model.GetTopUpByTradeNo(verifyInfo.ServiceTradeNo)
  305. if topUp == nil {
  306. log.Printf("易支付回调未找到订单: %v", verifyInfo)
  307. return
  308. }
  309. if topUp.Status == "pending" {
  310. topUp.Status = "success"
  311. err := topUp.Update()
  312. if err != nil {
  313. log.Printf("易支付回调更新订单失败: %v", topUp)
  314. return
  315. }
  316. //user, _ := model.GetUserById(topUp.UserId, false)
  317. //user.Quota += topUp.Amount * 500000
  318. dAmount := decimal.NewFromInt(int64(topUp.Amount))
  319. dQuotaPerUnit := decimal.NewFromFloat(common.QuotaPerUnit)
  320. quotaToAdd := int(dAmount.Mul(dQuotaPerUnit).IntPart())
  321. err = model.IncreaseUserQuota(topUp.UserId, quotaToAdd, true)
  322. if err != nil {
  323. log.Printf("易支付回调更新用户失败: %v", topUp)
  324. return
  325. }
  326. log.Printf("易支付回调更新用户成功 %v", topUp)
  327. model.RecordLog(topUp.UserId, model.LogTypeTopup, fmt.Sprintf("使用在线充值成功,充值金额: %v,支付金额:%f", logger.LogQuota(quotaToAdd), topUp.Money))
  328. }
  329. } else {
  330. log.Printf("易支付异常回调: %v", verifyInfo)
  331. }
  332. }
  333. func RequestAmount(c *gin.Context) {
  334. var req AmountRequest
  335. err := c.ShouldBindJSON(&req)
  336. if err != nil {
  337. c.JSON(200, gin.H{"message": "error", "data": "参数错误"})
  338. return
  339. }
  340. if req.Amount < getMinTopup() {
  341. c.JSON(200, gin.H{"message": "error", "data": fmt.Sprintf("充值数量不能小于 %d", getMinTopup())})
  342. return
  343. }
  344. id := c.GetInt("id")
  345. group, err := model.GetUserGroup(id, true)
  346. if err != nil {
  347. c.JSON(200, gin.H{"message": "error", "data": "获取用户分组失败"})
  348. return
  349. }
  350. payMoney := getPayMoney(req.Amount, group)
  351. if payMoney <= 0.01 {
  352. c.JSON(200, gin.H{"message": "error", "data": "充值金额过低"})
  353. return
  354. }
  355. c.JSON(200, gin.H{"message": "success", "data": strconv.FormatFloat(payMoney, 'f', 2, 64)})
  356. }
  357. func GetUserTopUps(c *gin.Context) {
  358. userId := c.GetInt("id")
  359. pageInfo := common.GetPageQuery(c)
  360. keyword := c.Query("keyword")
  361. var (
  362. topups []*model.TopUp
  363. total int64
  364. err error
  365. )
  366. if keyword != "" {
  367. topups, total, err = model.SearchUserTopUps(userId, keyword, pageInfo)
  368. } else {
  369. topups, total, err = model.GetUserTopUps(userId, pageInfo)
  370. }
  371. if err != nil {
  372. common.ApiError(c, err)
  373. return
  374. }
  375. pageInfo.SetTotal(int(total))
  376. pageInfo.SetItems(topups)
  377. common.ApiSuccess(c, pageInfo)
  378. }
  379. // GetAllTopUps 管理员获取全平台充值记录
  380. func GetAllTopUps(c *gin.Context) {
  381. pageInfo := common.GetPageQuery(c)
  382. keyword := c.Query("keyword")
  383. var (
  384. topups []*model.TopUp
  385. total int64
  386. err error
  387. )
  388. if keyword != "" {
  389. topups, total, err = model.SearchAllTopUps(keyword, pageInfo)
  390. } else {
  391. topups, total, err = model.GetAllTopUps(pageInfo)
  392. }
  393. if err != nil {
  394. common.ApiError(c, err)
  395. return
  396. }
  397. pageInfo.SetTotal(int(total))
  398. pageInfo.SetItems(topups)
  399. common.ApiSuccess(c, pageInfo)
  400. }
  401. type AdminCompleteTopupRequest struct {
  402. TradeNo string `json:"trade_no"`
  403. }
  404. // AdminCompleteTopUp 管理员补单接口
  405. func AdminCompleteTopUp(c *gin.Context) {
  406. var req AdminCompleteTopupRequest
  407. if err := c.ShouldBindJSON(&req); err != nil || req.TradeNo == "" {
  408. common.ApiErrorMsg(c, "参数错误")
  409. return
  410. }
  411. // 订单级互斥,防止并发补单
  412. LockOrder(req.TradeNo)
  413. defer UnlockOrder(req.TradeNo)
  414. if err := model.ManualCompleteTopUp(req.TradeNo); err != nil {
  415. common.ApiError(c, err)
  416. return
  417. }
  418. common.ApiSuccess(c, nil)
  419. }