topup_stripe.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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. if setting.StripeWebhookSecret == "" {
  132. log.Println("Stripe Webhook Secret 未配置,拒绝处理")
  133. c.AbortWithStatus(http.StatusForbidden)
  134. return
  135. }
  136. payload, err := io.ReadAll(c.Request.Body)
  137. if err != nil {
  138. log.Printf("解析Stripe Webhook参数失败: %v\n", err)
  139. c.AbortWithStatus(http.StatusServiceUnavailable)
  140. return
  141. }
  142. signature := c.GetHeader("Stripe-Signature")
  143. event, err := webhook.ConstructEventWithOptions(payload, signature, setting.StripeWebhookSecret, webhook.ConstructEventOptions{
  144. IgnoreAPIVersionMismatch: true,
  145. })
  146. if err != nil {
  147. log.Printf("Stripe Webhook验签失败: %v\n", err)
  148. c.AbortWithStatus(http.StatusBadRequest)
  149. return
  150. }
  151. switch event.Type {
  152. case stripe.EventTypeCheckoutSessionCompleted:
  153. sessionCompleted(event)
  154. case stripe.EventTypeCheckoutSessionExpired:
  155. sessionExpired(event)
  156. case stripe.EventTypeCheckoutSessionAsyncPaymentSucceeded:
  157. sessionAsyncPaymentSucceeded(event)
  158. case stripe.EventTypeCheckoutSessionAsyncPaymentFailed:
  159. sessionAsyncPaymentFailed(event)
  160. default:
  161. log.Printf("不支持的Stripe Webhook事件类型: %s\n", event.Type)
  162. }
  163. c.Status(http.StatusOK)
  164. }
  165. func sessionCompleted(event stripe.Event) {
  166. customerId := event.GetObjectValue("customer")
  167. referenceId := event.GetObjectValue("client_reference_id")
  168. status := event.GetObjectValue("status")
  169. if "complete" != status {
  170. log.Println("错误的Stripe Checkout完成状态:", status, ",", referenceId)
  171. return
  172. }
  173. paymentStatus := event.GetObjectValue("payment_status")
  174. if paymentStatus != "paid" {
  175. log.Printf("Stripe Checkout 支付尚未完成,payment_status: %s, ref: %s(等待异步支付结果)", paymentStatus, referenceId)
  176. return
  177. }
  178. fulfillOrder(event, referenceId, customerId)
  179. }
  180. // sessionAsyncPaymentSucceeded handles delayed payment methods (bank transfer, SEPA, etc.)
  181. // that confirm payment after the checkout session completes.
  182. func sessionAsyncPaymentSucceeded(event stripe.Event) {
  183. customerId := event.GetObjectValue("customer")
  184. referenceId := event.GetObjectValue("client_reference_id")
  185. log.Printf("Stripe 异步支付成功: %s", referenceId)
  186. fulfillOrder(event, referenceId, customerId)
  187. }
  188. // sessionAsyncPaymentFailed marks orders as failed when delayed payment methods
  189. // ultimately fail (e.g. bank transfer not received, SEPA rejected).
  190. func sessionAsyncPaymentFailed(event stripe.Event) {
  191. referenceId := event.GetObjectValue("client_reference_id")
  192. log.Printf("Stripe 异步支付失败: %s", referenceId)
  193. if len(referenceId) == 0 {
  194. log.Println("异步支付失败事件未提供支付单号")
  195. return
  196. }
  197. LockOrder(referenceId)
  198. defer UnlockOrder(referenceId)
  199. topUp := model.GetTopUpByTradeNo(referenceId)
  200. if topUp == nil {
  201. log.Println("异步支付失败,充值订单不存在:", referenceId)
  202. return
  203. }
  204. if topUp.Status != common.TopUpStatusPending {
  205. log.Printf("异步支付失败,订单状态非pending: %s, ref: %s", topUp.Status, referenceId)
  206. return
  207. }
  208. topUp.Status = common.TopUpStatusFailed
  209. if err := topUp.Update(); err != nil {
  210. log.Printf("标记充值订单失败出错: %v, ref: %s", err, referenceId)
  211. return
  212. }
  213. log.Printf("充值订单已标记为失败: %s", referenceId)
  214. }
  215. // fulfillOrder is the shared logic for crediting quota after payment is confirmed.
  216. func fulfillOrder(event stripe.Event, referenceId string, customerId string) {
  217. if len(referenceId) == 0 {
  218. log.Println("未提供支付单号")
  219. return
  220. }
  221. LockOrder(referenceId)
  222. defer UnlockOrder(referenceId)
  223. payload := map[string]any{
  224. "customer": customerId,
  225. "amount_total": event.GetObjectValue("amount_total"),
  226. "currency": strings.ToUpper(event.GetObjectValue("currency")),
  227. "event_type": string(event.Type),
  228. }
  229. if err := model.CompleteSubscriptionOrder(referenceId, common.GetJsonString(payload)); err == nil {
  230. return
  231. } else if err != nil && !errors.Is(err, model.ErrSubscriptionOrderNotFound) {
  232. log.Println("complete subscription order failed:", err.Error(), referenceId)
  233. return
  234. }
  235. err := model.Recharge(referenceId, customerId)
  236. if err != nil {
  237. log.Println(err.Error(), referenceId)
  238. return
  239. }
  240. total, _ := strconv.ParseFloat(event.GetObjectValue("amount_total"), 64)
  241. currency := strings.ToUpper(event.GetObjectValue("currency"))
  242. log.Printf("收到款项:%s, %.2f(%s)", referenceId, total/100, currency)
  243. }
  244. func sessionExpired(event stripe.Event) {
  245. referenceId := event.GetObjectValue("client_reference_id")
  246. status := event.GetObjectValue("status")
  247. if "expired" != status {
  248. log.Println("错误的Stripe Checkout过期状态:", status, ",", referenceId)
  249. return
  250. }
  251. if len(referenceId) == 0 {
  252. log.Println("未提供支付单号")
  253. return
  254. }
  255. // Subscription order expiration
  256. LockOrder(referenceId)
  257. defer UnlockOrder(referenceId)
  258. if err := model.ExpireSubscriptionOrder(referenceId); err == nil {
  259. return
  260. } else if err != nil && !errors.Is(err, model.ErrSubscriptionOrderNotFound) {
  261. log.Println("过期订阅订单失败", referenceId, ", err:", err.Error())
  262. return
  263. }
  264. topUp := model.GetTopUpByTradeNo(referenceId)
  265. if topUp == nil {
  266. log.Println("充值订单不存在", referenceId)
  267. return
  268. }
  269. if topUp.Status != common.TopUpStatusPending {
  270. log.Println("充值订单状态错误", referenceId)
  271. }
  272. topUp.Status = common.TopUpStatusExpired
  273. err := topUp.Update()
  274. if err != nil {
  275. log.Println("过期充值订单失败", referenceId, ", err:", err.Error())
  276. return
  277. }
  278. log.Println("充值订单已过期", referenceId)
  279. }
  280. // genStripeLink generates a Stripe Checkout session URL for payment.
  281. // It creates a new checkout session with the specified parameters and returns the payment URL.
  282. //
  283. // Parameters:
  284. // - referenceId: unique reference identifier for the transaction
  285. // - customerId: existing Stripe customer ID (empty string if new customer)
  286. // - email: customer email address for new customer creation
  287. // - amount: quantity of units to purchase
  288. // - successURL: custom URL to redirect after successful payment (empty for default)
  289. // - cancelURL: custom URL to redirect when payment is canceled (empty for default)
  290. //
  291. // Returns the checkout session URL or an error if the session creation fails.
  292. func genStripeLink(referenceId string, customerId string, email string, amount int64, successURL string, cancelURL string) (string, error) {
  293. if !strings.HasPrefix(setting.StripeApiSecret, "sk_") && !strings.HasPrefix(setting.StripeApiSecret, "rk_") {
  294. return "", fmt.Errorf("无效的Stripe API密钥")
  295. }
  296. stripe.Key = setting.StripeApiSecret
  297. // Use custom URLs if provided, otherwise use defaults
  298. if successURL == "" {
  299. successURL = system_setting.ServerAddress + "/console/log"
  300. }
  301. if cancelURL == "" {
  302. cancelURL = system_setting.ServerAddress + "/console/topup"
  303. }
  304. params := &stripe.CheckoutSessionParams{
  305. ClientReferenceID: stripe.String(referenceId),
  306. SuccessURL: stripe.String(successURL),
  307. CancelURL: stripe.String(cancelURL),
  308. LineItems: []*stripe.CheckoutSessionLineItemParams{
  309. {
  310. Price: stripe.String(setting.StripePriceId),
  311. Quantity: stripe.Int64(amount),
  312. },
  313. },
  314. Mode: stripe.String(string(stripe.CheckoutSessionModePayment)),
  315. AllowPromotionCodes: stripe.Bool(setting.StripePromotionCodesEnabled),
  316. }
  317. if "" == customerId {
  318. if "" != email {
  319. params.CustomerEmail = stripe.String(email)
  320. }
  321. params.CustomerCreation = stripe.String(string(stripe.CheckoutSessionCustomerCreationAlways))
  322. } else {
  323. params.Customer = stripe.String(customerId)
  324. }
  325. result, err := session.New(params)
  326. if err != nil {
  327. return "", err
  328. }
  329. return result.URL, nil
  330. }
  331. func GetChargedAmount(count float64, user model.User) float64 {
  332. topUpGroupRatio := common.GetTopupGroupRatio(user.Group)
  333. if topUpGroupRatio == 0 {
  334. topUpGroupRatio = 1
  335. }
  336. return count * topUpGroupRatio
  337. }
  338. func getStripePayMoney(amount float64, group string) float64 {
  339. originalAmount := amount
  340. if operation_setting.GetQuotaDisplayType() == operation_setting.QuotaDisplayTypeTokens {
  341. amount = amount / common.QuotaPerUnit
  342. }
  343. // Using float64 for monetary calculations is acceptable here due to the small amounts involved
  344. topupGroupRatio := common.GetTopupGroupRatio(group)
  345. if topupGroupRatio == 0 {
  346. topupGroupRatio = 1
  347. }
  348. // apply optional preset discount by the original request amount (if configured), default 1.0
  349. discount := 1.0
  350. if ds, ok := operation_setting.GetPaymentSetting().AmountDiscount[int(originalAmount)]; ok {
  351. if ds > 0 {
  352. discount = ds
  353. }
  354. }
  355. payMoney := amount * setting.StripeUnitPrice * topupGroupRatio * discount
  356. return payMoney
  357. }
  358. func getStripeMinTopup() int64 {
  359. minTopup := setting.StripeMinTopUp
  360. if operation_setting.GetQuotaDisplayType() == operation_setting.QuotaDisplayTypeTokens {
  361. minTopup = minTopup * int(common.QuotaPerUnit)
  362. }
  363. return int64(minTopup)
  364. }