topup_stripe.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. package controller
  2. import (
  3. "fmt"
  4. "io"
  5. "log"
  6. "net/http"
  7. "strconv"
  8. "strings"
  9. "time"
  10. "github.com/QuantumNous/new-api/common"
  11. "github.com/QuantumNous/new-api/model"
  12. "github.com/QuantumNous/new-api/setting"
  13. "github.com/QuantumNous/new-api/setting/operation_setting"
  14. "github.com/QuantumNous/new-api/setting/system_setting"
  15. "github.com/gin-gonic/gin"
  16. "github.com/stripe/stripe-go/v81"
  17. "github.com/stripe/stripe-go/v81/checkout/session"
  18. "github.com/stripe/stripe-go/v81/webhook"
  19. "github.com/thanhpk/randstr"
  20. )
  21. const (
  22. PaymentMethodStripe = "stripe"
  23. )
  24. var stripeAdaptor = &StripeAdaptor{}
  25. type StripePayRequest struct {
  26. Amount int64 `json:"amount"`
  27. PaymentMethod string `json:"payment_method"`
  28. SuccessURL string `json:"success_url,omitempty"`
  29. CancelURL string `json:"cancel_url,omitempty"`
  30. }
  31. type StripeAdaptor struct {
  32. }
  33. func (*StripeAdaptor) RequestAmount(c *gin.Context, req *StripePayRequest) {
  34. if req.Amount < getStripeMinTopup() {
  35. c.JSON(200, gin.H{"message": "error", "data": fmt.Sprintf("充值数量不能小于 %d", getStripeMinTopup())})
  36. return
  37. }
  38. id := c.GetInt("id")
  39. group, err := model.GetUserGroup(id, true)
  40. if err != nil {
  41. c.JSON(200, gin.H{"message": "error", "data": "获取用户分组失败"})
  42. return
  43. }
  44. payMoney := getStripePayMoney(float64(req.Amount), group)
  45. if payMoney <= 0.01 {
  46. c.JSON(200, gin.H{"message": "error", "data": "充值金额过低"})
  47. return
  48. }
  49. c.JSON(200, gin.H{"message": "success", "data": strconv.FormatFloat(payMoney, 'f', 2, 64)})
  50. }
  51. func (*StripeAdaptor) RequestPay(c *gin.Context, req *StripePayRequest) {
  52. if req.PaymentMethod != PaymentMethodStripe {
  53. c.JSON(200, gin.H{"message": "error", "data": "不支持的支付渠道"})
  54. return
  55. }
  56. if req.Amount < getStripeMinTopup() {
  57. c.JSON(200, gin.H{"message": fmt.Sprintf("充值数量不能小于 %d", getStripeMinTopup()), "data": 10})
  58. return
  59. }
  60. if req.Amount > 10000 {
  61. c.JSON(200, gin.H{"message": "充值数量不能大于 10000", "data": 10})
  62. return
  63. }
  64. id := c.GetInt("id")
  65. user, _ := model.GetUserById(id, false)
  66. chargedMoney := GetChargedAmount(float64(req.Amount), *user)
  67. reference := fmt.Sprintf("new-api-ref-%d-%d-%s", user.Id, time.Now().UnixMilli(), randstr.String(4))
  68. referenceId := "ref_" + common.Sha1([]byte(reference))
  69. payLink, err := genStripeLink(referenceId, user.StripeCustomer, user.Email, req.Amount, req.SuccessURL, req.CancelURL)
  70. if err != nil {
  71. log.Println("获取Stripe Checkout支付链接失败", err)
  72. c.JSON(200, gin.H{"message": "error", "data": "拉起支付失败"})
  73. return
  74. }
  75. topUp := &model.TopUp{
  76. UserId: id,
  77. Amount: req.Amount,
  78. Money: chargedMoney,
  79. TradeNo: referenceId,
  80. PaymentMethod: PaymentMethodStripe,
  81. CreateTime: time.Now().Unix(),
  82. Status: common.TopUpStatusPending,
  83. }
  84. err = topUp.Insert()
  85. if err != nil {
  86. c.JSON(200, gin.H{"message": "error", "data": "创建订单失败"})
  87. return
  88. }
  89. c.JSON(200, gin.H{
  90. "message": "success",
  91. "data": gin.H{
  92. "pay_link": payLink,
  93. },
  94. })
  95. }
  96. func RequestStripeAmount(c *gin.Context) {
  97. var req StripePayRequest
  98. err := c.ShouldBindJSON(&req)
  99. if err != nil {
  100. c.JSON(200, gin.H{"message": "error", "data": "参数错误"})
  101. return
  102. }
  103. stripeAdaptor.RequestAmount(c, &req)
  104. }
  105. func RequestStripePay(c *gin.Context) {
  106. var req StripePayRequest
  107. err := c.ShouldBindJSON(&req)
  108. if err != nil {
  109. c.JSON(200, gin.H{"message": "error", "data": "参数错误"})
  110. return
  111. }
  112. stripeAdaptor.RequestPay(c, &req)
  113. }
  114. func StripeWebhook(c *gin.Context) {
  115. payload, err := io.ReadAll(c.Request.Body)
  116. if err != nil {
  117. log.Printf("解析Stripe Webhook参数失败: %v\n", err)
  118. c.AbortWithStatus(http.StatusServiceUnavailable)
  119. return
  120. }
  121. signature := c.GetHeader("Stripe-Signature")
  122. endpointSecret := setting.StripeWebhookSecret
  123. event, err := webhook.ConstructEventWithOptions(payload, signature, endpointSecret, webhook.ConstructEventOptions{
  124. IgnoreAPIVersionMismatch: true,
  125. })
  126. if err != nil {
  127. log.Printf("Stripe Webhook验签失败: %v\n", err)
  128. c.AbortWithStatus(http.StatusBadRequest)
  129. return
  130. }
  131. switch event.Type {
  132. case stripe.EventTypeCheckoutSessionCompleted:
  133. sessionCompleted(event)
  134. case stripe.EventTypeCheckoutSessionExpired:
  135. sessionExpired(event)
  136. default:
  137. log.Printf("不支持的Stripe Webhook事件类型: %s\n", event.Type)
  138. }
  139. c.Status(http.StatusOK)
  140. }
  141. func sessionCompleted(event stripe.Event) {
  142. customerId := event.GetObjectValue("customer")
  143. referenceId := event.GetObjectValue("client_reference_id")
  144. status := event.GetObjectValue("status")
  145. if "complete" != status {
  146. log.Println("错误的Stripe Checkout完成状态:", status, ",", referenceId)
  147. return
  148. }
  149. err := model.Recharge(referenceId, customerId)
  150. if err != nil {
  151. log.Println(err.Error(), referenceId)
  152. return
  153. }
  154. total, _ := strconv.ParseFloat(event.GetObjectValue("amount_total"), 64)
  155. currency := strings.ToUpper(event.GetObjectValue("currency"))
  156. log.Printf("收到款项:%s, %.2f(%s)", referenceId, total/100, currency)
  157. }
  158. func sessionExpired(event stripe.Event) {
  159. referenceId := event.GetObjectValue("client_reference_id")
  160. status := event.GetObjectValue("status")
  161. if "expired" != status {
  162. log.Println("错误的Stripe Checkout过期状态:", status, ",", referenceId)
  163. return
  164. }
  165. if len(referenceId) == 0 {
  166. log.Println("未提供支付单号")
  167. return
  168. }
  169. topUp := model.GetTopUpByTradeNo(referenceId)
  170. if topUp == nil {
  171. log.Println("充值订单不存在", referenceId)
  172. return
  173. }
  174. if topUp.Status != common.TopUpStatusPending {
  175. log.Println("充值订单状态错误", referenceId)
  176. }
  177. topUp.Status = common.TopUpStatusExpired
  178. err := topUp.Update()
  179. if err != nil {
  180. log.Println("过期充值订单失败", referenceId, ", err:", err.Error())
  181. return
  182. }
  183. log.Println("充值订单已过期", referenceId)
  184. }
  185. func genStripeLink(referenceId string, customerId string, email string, amount int64, successURL string, cancelURL string) (string, error) {
  186. if !strings.HasPrefix(setting.StripeApiSecret, "sk_") && !strings.HasPrefix(setting.StripeApiSecret, "rk_") {
  187. return "", fmt.Errorf("无效的Stripe API密钥")
  188. }
  189. stripe.Key = setting.StripeApiSecret
  190. // Use custom URLs if provided, otherwise use defaults
  191. if successURL == "" {
  192. successURL = system_setting.ServerAddress + "/console/log"
  193. }
  194. if cancelURL == "" {
  195. cancelURL = system_setting.ServerAddress + "/console/topup"
  196. }
  197. params := &stripe.CheckoutSessionParams{
  198. ClientReferenceID: stripe.String(referenceId),
  199. SuccessURL: stripe.String(successURL),
  200. CancelURL: stripe.String(cancelURL),
  201. LineItems: []*stripe.CheckoutSessionLineItemParams{
  202. {
  203. Price: stripe.String(setting.StripePriceId),
  204. Quantity: stripe.Int64(amount),
  205. },
  206. },
  207. Mode: stripe.String(string(stripe.CheckoutSessionModePayment)),
  208. AllowPromotionCodes: stripe.Bool(setting.StripePromotionCodesEnabled),
  209. }
  210. if "" == customerId {
  211. if "" != email {
  212. params.CustomerEmail = stripe.String(email)
  213. }
  214. params.CustomerCreation = stripe.String(string(stripe.CheckoutSessionCustomerCreationAlways))
  215. } else {
  216. params.Customer = stripe.String(customerId)
  217. }
  218. result, err := session.New(params)
  219. if err != nil {
  220. return "", err
  221. }
  222. return result.URL, nil
  223. }
  224. func GetChargedAmount(count float64, user model.User) float64 {
  225. topUpGroupRatio := common.GetTopupGroupRatio(user.Group)
  226. if topUpGroupRatio == 0 {
  227. topUpGroupRatio = 1
  228. }
  229. return count * topUpGroupRatio
  230. }
  231. func getStripePayMoney(amount float64, group string) float64 {
  232. originalAmount := amount
  233. if operation_setting.GetQuotaDisplayType() == operation_setting.QuotaDisplayTypeTokens {
  234. amount = amount / common.QuotaPerUnit
  235. }
  236. // Using float64 for monetary calculations is acceptable here due to the small amounts involved
  237. topupGroupRatio := common.GetTopupGroupRatio(group)
  238. if topupGroupRatio == 0 {
  239. topupGroupRatio = 1
  240. }
  241. // apply optional preset discount by the original request amount (if configured), default 1.0
  242. discount := 1.0
  243. if ds, ok := operation_setting.GetPaymentSetting().AmountDiscount[int(originalAmount)]; ok {
  244. if ds > 0 {
  245. discount = ds
  246. }
  247. }
  248. payMoney := amount * setting.StripeUnitPrice * topupGroupRatio * discount
  249. return payMoney
  250. }
  251. func getStripeMinTopup() int64 {
  252. minTopup := setting.StripeMinTopUp
  253. if operation_setting.GetQuotaDisplayType() == operation_setting.QuotaDisplayTypeTokens {
  254. minTopup = minTopup * int(common.QuotaPerUnit)
  255. }
  256. return int64(minTopup)
  257. }