topup_stripe.go 9.8 KB

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