topup_stripe.go 13 KB

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