topup_stripe.go 9.4 KB

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