topup_stripe.go 8.0 KB

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