topup_stripe.go 11 KB

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