topup_stripe.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. package controller
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "github.com/QuantumNous/new-api/common"
  12. "github.com/QuantumNous/new-api/logger"
  13. "github.com/QuantumNous/new-api/model"
  14. "github.com/QuantumNous/new-api/setting"
  15. "github.com/QuantumNous/new-api/setting/operation_setting"
  16. "github.com/QuantumNous/new-api/setting/system_setting"
  17. "github.com/gin-gonic/gin"
  18. "github.com/stripe/stripe-go/v81"
  19. "github.com/stripe/stripe-go/v81/checkout/session"
  20. "github.com/stripe/stripe-go/v81/webhook"
  21. "github.com/thanhpk/randstr"
  22. )
  23. var stripeAdaptor = &StripeAdaptor{}
  24. // StripePayRequest represents a payment request for Stripe checkout.
  25. type StripePayRequest struct {
  26. // Amount is the quantity of units to purchase.
  27. Amount int64 `json:"amount"`
  28. // PaymentMethod specifies the payment method (e.g., "stripe").
  29. PaymentMethod string `json:"payment_method"`
  30. // SuccessURL is the optional custom URL to redirect after successful payment.
  31. // If empty, defaults to the server's console log page.
  32. SuccessURL string `json:"success_url,omitempty"`
  33. // CancelURL is the optional custom URL to redirect when payment is canceled.
  34. // If empty, defaults to the server's console topup page.
  35. CancelURL string `json:"cancel_url,omitempty"`
  36. }
  37. type StripeAdaptor struct {
  38. }
  39. func (*StripeAdaptor) RequestAmount(c *gin.Context, req *StripePayRequest) {
  40. if req.Amount < getStripeMinTopup() {
  41. c.JSON(http.StatusOK, gin.H{"message": "error", "data": fmt.Sprintf("充值数量不能小于 %d", getStripeMinTopup())})
  42. return
  43. }
  44. id := c.GetInt("id")
  45. group, err := model.GetUserGroup(id, true)
  46. if err != nil {
  47. c.JSON(http.StatusOK, gin.H{"message": "error", "data": "获取用户分组失败"})
  48. return
  49. }
  50. payMoney := getStripePayMoney(float64(req.Amount), group)
  51. if payMoney <= 0.01 {
  52. c.JSON(http.StatusOK, gin.H{"message": "error", "data": "充值金额过低"})
  53. return
  54. }
  55. c.JSON(http.StatusOK, gin.H{"message": "success", "data": strconv.FormatFloat(payMoney, 'f', 2, 64)})
  56. }
  57. func (*StripeAdaptor) RequestPay(c *gin.Context, req *StripePayRequest) {
  58. if req.PaymentMethod != model.PaymentMethodStripe {
  59. c.JSON(http.StatusOK, gin.H{"message": "error", "data": "不支持的支付渠道"})
  60. return
  61. }
  62. if req.Amount < getStripeMinTopup() {
  63. c.JSON(http.StatusOK, gin.H{"message": fmt.Sprintf("充值数量不能小于 %d", getStripeMinTopup()), "data": 10})
  64. return
  65. }
  66. if req.Amount > 10000 {
  67. c.JSON(http.StatusOK, gin.H{"message": "充值数量不能大于 10000", "data": 10})
  68. return
  69. }
  70. if req.SuccessURL != "" && common.ValidateRedirectURL(req.SuccessURL) != nil {
  71. c.JSON(http.StatusBadRequest, gin.H{"message": "支付成功重定向URL不在可信任域名列表中", "data": ""})
  72. return
  73. }
  74. if req.CancelURL != "" && common.ValidateRedirectURL(req.CancelURL) != nil {
  75. c.JSON(http.StatusBadRequest, gin.H{"message": "支付取消重定向URL不在可信任域名列表中", "data": ""})
  76. return
  77. }
  78. id := c.GetInt("id")
  79. user, _ := model.GetUserById(id, false)
  80. chargedMoney := GetChargedAmount(float64(req.Amount), *user)
  81. reference := fmt.Sprintf("new-api-ref-%d-%d-%s", user.Id, time.Now().UnixMilli(), randstr.String(4))
  82. referenceId := "ref_" + common.Sha1([]byte(reference))
  83. payLink, err := genStripeLink(referenceId, user.StripeCustomer, user.Email, req.Amount, req.SuccessURL, req.CancelURL)
  84. if err != nil {
  85. logger.LogError(c.Request.Context(), fmt.Sprintf("Stripe 创建 Checkout Session 失败 user_id=%d trade_no=%s amount=%d error=%q", id, referenceId, req.Amount, err.Error()))
  86. c.JSON(http.StatusOK, gin.H{"message": "error", "data": "拉起支付失败"})
  87. return
  88. }
  89. topUp := &model.TopUp{
  90. UserId: id,
  91. Amount: req.Amount,
  92. Money: chargedMoney,
  93. TradeNo: referenceId,
  94. PaymentMethod: model.PaymentMethodStripe,
  95. PaymentProvider: model.PaymentProviderStripe,
  96. CreateTime: time.Now().Unix(),
  97. Status: common.TopUpStatusPending,
  98. }
  99. err = topUp.Insert()
  100. if err != nil {
  101. logger.LogError(c.Request.Context(), fmt.Sprintf("Stripe 创建充值订单失败 user_id=%d trade_no=%s amount=%d error=%q", id, referenceId, req.Amount, err.Error()))
  102. c.JSON(http.StatusOK, gin.H{"message": "error", "data": "创建订单失败"})
  103. return
  104. }
  105. logger.LogInfo(c.Request.Context(), fmt.Sprintf("Stripe 充值订单创建成功 user_id=%d trade_no=%s amount=%d money=%.2f", id, referenceId, req.Amount, chargedMoney))
  106. c.JSON(http.StatusOK, gin.H{
  107. "message": "success",
  108. "data": gin.H{
  109. "pay_link": payLink,
  110. },
  111. })
  112. }
  113. func RequestStripeAmount(c *gin.Context) {
  114. var req StripePayRequest
  115. err := c.ShouldBindJSON(&req)
  116. if err != nil {
  117. c.JSON(http.StatusOK, gin.H{"message": "error", "data": "参数错误"})
  118. return
  119. }
  120. stripeAdaptor.RequestAmount(c, &req)
  121. }
  122. func RequestStripePay(c *gin.Context) {
  123. var req StripePayRequest
  124. err := c.ShouldBindJSON(&req)
  125. if err != nil {
  126. c.JSON(http.StatusOK, gin.H{"message": "error", "data": "参数错误"})
  127. return
  128. }
  129. stripeAdaptor.RequestPay(c, &req)
  130. }
  131. func StripeWebhook(c *gin.Context) {
  132. ctx := c.Request.Context()
  133. if !isStripeWebhookEnabled() {
  134. logger.LogWarn(ctx, fmt.Sprintf("Stripe webhook 被拒绝 reason=webhook_disabled path=%q client_ip=%s", c.Request.RequestURI, c.ClientIP()))
  135. c.AbortWithStatus(http.StatusForbidden)
  136. return
  137. }
  138. payload, err := io.ReadAll(c.Request.Body)
  139. if err != nil {
  140. logger.LogError(ctx, fmt.Sprintf("Stripe webhook 读取请求体失败 path=%q client_ip=%s error=%q", c.Request.RequestURI, c.ClientIP(), err.Error()))
  141. c.AbortWithStatus(http.StatusServiceUnavailable)
  142. return
  143. }
  144. signature := c.GetHeader("Stripe-Signature")
  145. logger.LogInfo(ctx, fmt.Sprintf("Stripe webhook 收到请求 path=%q client_ip=%s signature=%q body=%q", c.Request.RequestURI, c.ClientIP(), signature, string(payload)))
  146. event, err := webhook.ConstructEventWithOptions(payload, signature, setting.StripeWebhookSecret, webhook.ConstructEventOptions{
  147. IgnoreAPIVersionMismatch: true,
  148. })
  149. if err != nil {
  150. logger.LogWarn(ctx, fmt.Sprintf("Stripe webhook 验签失败 path=%q client_ip=%s error=%q", c.Request.RequestURI, c.ClientIP(), err.Error()))
  151. c.AbortWithStatus(http.StatusBadRequest)
  152. return
  153. }
  154. callerIp := c.ClientIP()
  155. logger.LogInfo(ctx, fmt.Sprintf("Stripe webhook 验签成功 event_type=%s client_ip=%s path=%q", string(event.Type), callerIp, c.Request.RequestURI))
  156. switch event.Type {
  157. case stripe.EventTypeCheckoutSessionCompleted:
  158. sessionCompleted(ctx, event, callerIp)
  159. case stripe.EventTypeCheckoutSessionExpired:
  160. sessionExpired(ctx, event)
  161. case stripe.EventTypeCheckoutSessionAsyncPaymentSucceeded:
  162. sessionAsyncPaymentSucceeded(ctx, event, callerIp)
  163. case stripe.EventTypeCheckoutSessionAsyncPaymentFailed:
  164. sessionAsyncPaymentFailed(ctx, event, callerIp)
  165. default:
  166. logger.LogInfo(ctx, fmt.Sprintf("Stripe webhook 忽略事件 event_type=%s client_ip=%s", string(event.Type), callerIp))
  167. }
  168. c.Status(http.StatusOK)
  169. }
  170. func sessionCompleted(ctx context.Context, event stripe.Event, callerIp string) {
  171. customerId := event.GetObjectValue("customer")
  172. referenceId := event.GetObjectValue("client_reference_id")
  173. status := event.GetObjectValue("status")
  174. if "complete" != status {
  175. logger.LogWarn(ctx, fmt.Sprintf("Stripe checkout.completed 状态异常,忽略处理 trade_no=%s status=%s client_ip=%s", referenceId, status, callerIp))
  176. return
  177. }
  178. paymentStatus := event.GetObjectValue("payment_status")
  179. if paymentStatus != "paid" {
  180. logger.LogInfo(ctx, fmt.Sprintf("Stripe Checkout 支付未完成,等待异步结果 trade_no=%s payment_status=%s client_ip=%s", referenceId, paymentStatus, callerIp))
  181. return
  182. }
  183. fulfillOrder(ctx, event, referenceId, customerId, callerIp)
  184. }
  185. // sessionAsyncPaymentSucceeded handles delayed payment methods (bank transfer, SEPA, etc.)
  186. // that confirm payment after the checkout session completes.
  187. func sessionAsyncPaymentSucceeded(ctx context.Context, event stripe.Event, callerIp string) {
  188. customerId := event.GetObjectValue("customer")
  189. referenceId := event.GetObjectValue("client_reference_id")
  190. logger.LogInfo(ctx, fmt.Sprintf("Stripe 异步支付成功 trade_no=%s client_ip=%s", referenceId, callerIp))
  191. fulfillOrder(ctx, event, referenceId, customerId, callerIp)
  192. }
  193. // sessionAsyncPaymentFailed marks orders as failed when delayed payment methods
  194. // ultimately fail (e.g. bank transfer not received, SEPA rejected).
  195. func sessionAsyncPaymentFailed(ctx context.Context, event stripe.Event, callerIp string) {
  196. referenceId := event.GetObjectValue("client_reference_id")
  197. logger.LogWarn(ctx, fmt.Sprintf("Stripe 异步支付失败 trade_no=%s client_ip=%s", referenceId, callerIp))
  198. if len(referenceId) == 0 {
  199. logger.LogWarn(ctx, fmt.Sprintf("Stripe 异步支付失败事件缺少订单号 client_ip=%s", callerIp))
  200. return
  201. }
  202. LockOrder(referenceId)
  203. defer UnlockOrder(referenceId)
  204. topUp := model.GetTopUpByTradeNo(referenceId)
  205. if topUp == nil {
  206. logger.LogWarn(ctx, fmt.Sprintf("Stripe 异步支付失败但本地订单不存在 trade_no=%s client_ip=%s", referenceId, callerIp))
  207. return
  208. }
  209. if topUp.PaymentProvider != model.PaymentProviderStripe {
  210. logger.LogWarn(ctx, fmt.Sprintf("Stripe 异步支付失败但订单支付网关不匹配 trade_no=%s payment_provider=%s client_ip=%s", referenceId, topUp.PaymentProvider, callerIp))
  211. return
  212. }
  213. if topUp.Status != common.TopUpStatusPending {
  214. logger.LogInfo(ctx, fmt.Sprintf("Stripe 异步支付失败但订单状态非 pending,忽略处理 trade_no=%s status=%s client_ip=%s", referenceId, topUp.Status, callerIp))
  215. return
  216. }
  217. topUp.Status = common.TopUpStatusFailed
  218. if err := topUp.Update(); err != nil {
  219. logger.LogError(ctx, fmt.Sprintf("Stripe 标记充值订单失败状态失败 trade_no=%s client_ip=%s error=%q", referenceId, callerIp, err.Error()))
  220. return
  221. }
  222. logger.LogInfo(ctx, fmt.Sprintf("Stripe 充值订单已标记为失败 trade_no=%s client_ip=%s", referenceId, callerIp))
  223. }
  224. // fulfillOrder is the shared logic for crediting quota after payment is confirmed.
  225. func fulfillOrder(ctx context.Context, event stripe.Event, referenceId string, customerId string, callerIp string) {
  226. if len(referenceId) == 0 {
  227. logger.LogWarn(ctx, fmt.Sprintf("Stripe 完成订单时缺少订单号 client_ip=%s", callerIp))
  228. return
  229. }
  230. LockOrder(referenceId)
  231. defer UnlockOrder(referenceId)
  232. payload := map[string]any{
  233. "customer": customerId,
  234. "amount_total": event.GetObjectValue("amount_total"),
  235. "currency": strings.ToUpper(event.GetObjectValue("currency")),
  236. "event_type": string(event.Type),
  237. }
  238. if err := model.CompleteSubscriptionOrder(referenceId, common.GetJsonString(payload), model.PaymentProviderStripe, ""); err == nil {
  239. logger.LogInfo(ctx, fmt.Sprintf("Stripe 订阅订单处理成功 trade_no=%s event_type=%s client_ip=%s", referenceId, string(event.Type), callerIp))
  240. return
  241. } else if err != nil && !errors.Is(err, model.ErrSubscriptionOrderNotFound) {
  242. logger.LogError(ctx, fmt.Sprintf("Stripe 订阅订单处理失败 trade_no=%s event_type=%s client_ip=%s error=%q", referenceId, string(event.Type), callerIp, err.Error()))
  243. return
  244. }
  245. err := model.Recharge(referenceId, customerId, callerIp)
  246. if err != nil {
  247. logger.LogError(ctx, fmt.Sprintf("Stripe 充值处理失败 trade_no=%s event_type=%s client_ip=%s error=%q", referenceId, string(event.Type), callerIp, err.Error()))
  248. return
  249. }
  250. total, _ := strconv.ParseFloat(event.GetObjectValue("amount_total"), 64)
  251. currency := strings.ToUpper(event.GetObjectValue("currency"))
  252. logger.LogInfo(ctx, fmt.Sprintf("Stripe 充值成功 trade_no=%s amount_total=%.2f currency=%s event_type=%s client_ip=%s", referenceId, total/100, currency, string(event.Type), callerIp))
  253. }
  254. func sessionExpired(ctx context.Context, event stripe.Event) {
  255. referenceId := event.GetObjectValue("client_reference_id")
  256. status := event.GetObjectValue("status")
  257. if "expired" != status {
  258. logger.LogWarn(ctx, fmt.Sprintf("Stripe checkout.expired 状态异常,忽略处理 trade_no=%s status=%s", referenceId, status))
  259. return
  260. }
  261. if len(referenceId) == 0 {
  262. logger.LogWarn(ctx, "Stripe checkout.expired 缺少订单号")
  263. return
  264. }
  265. // Subscription order expiration
  266. LockOrder(referenceId)
  267. defer UnlockOrder(referenceId)
  268. if err := model.ExpireSubscriptionOrder(referenceId, model.PaymentProviderStripe); err == nil {
  269. logger.LogInfo(ctx, fmt.Sprintf("Stripe 订阅订单已过期 trade_no=%s", referenceId))
  270. return
  271. } else if err != nil && !errors.Is(err, model.ErrSubscriptionOrderNotFound) {
  272. logger.LogError(ctx, fmt.Sprintf("Stripe 订阅订单过期处理失败 trade_no=%s error=%q", referenceId, err.Error()))
  273. return
  274. }
  275. err := model.UpdatePendingTopUpStatus(referenceId, model.PaymentProviderStripe, common.TopUpStatusExpired)
  276. if errors.Is(err, model.ErrTopUpNotFound) {
  277. logger.LogWarn(ctx, fmt.Sprintf("Stripe 充值订单不存在,无法标记过期 trade_no=%s", referenceId))
  278. return
  279. }
  280. if err != nil {
  281. logger.LogError(ctx, fmt.Sprintf("Stripe 充值订单过期处理失败 trade_no=%s error=%q", referenceId, err.Error()))
  282. return
  283. }
  284. logger.LogInfo(ctx, fmt.Sprintf("Stripe 充值订单已过期 trade_no=%s", referenceId))
  285. }
  286. // genStripeLink generates a Stripe Checkout session URL for payment.
  287. // It creates a new checkout session with the specified parameters and returns the payment URL.
  288. //
  289. // Parameters:
  290. // - referenceId: unique reference identifier for the transaction
  291. // - customerId: existing Stripe customer ID (empty string if new customer)
  292. // - email: customer email address for new customer creation
  293. // - amount: quantity of units to purchase
  294. // - successURL: custom URL to redirect after successful payment (empty for default)
  295. // - cancelURL: custom URL to redirect when payment is canceled (empty for default)
  296. //
  297. // Returns the checkout session URL or an error if the session creation fails.
  298. func genStripeLink(referenceId string, customerId string, email string, amount int64, successURL string, cancelURL string) (string, error) {
  299. if !strings.HasPrefix(setting.StripeApiSecret, "sk_") && !strings.HasPrefix(setting.StripeApiSecret, "rk_") {
  300. return "", fmt.Errorf("无效的Stripe API密钥")
  301. }
  302. stripe.Key = setting.StripeApiSecret
  303. // Use custom URLs if provided, otherwise use defaults
  304. if successURL == "" {
  305. successURL = system_setting.ServerAddress + "/console/log"
  306. }
  307. if cancelURL == "" {
  308. cancelURL = system_setting.ServerAddress + "/console/topup"
  309. }
  310. params := &stripe.CheckoutSessionParams{
  311. ClientReferenceID: stripe.String(referenceId),
  312. SuccessURL: stripe.String(successURL),
  313. CancelURL: stripe.String(cancelURL),
  314. LineItems: []*stripe.CheckoutSessionLineItemParams{
  315. {
  316. Price: stripe.String(setting.StripePriceId),
  317. Quantity: stripe.Int64(amount),
  318. },
  319. },
  320. Mode: stripe.String(string(stripe.CheckoutSessionModePayment)),
  321. AllowPromotionCodes: stripe.Bool(setting.StripePromotionCodesEnabled),
  322. }
  323. if "" == customerId {
  324. if "" != email {
  325. params.CustomerEmail = stripe.String(email)
  326. }
  327. params.CustomerCreation = stripe.String(string(stripe.CheckoutSessionCustomerCreationAlways))
  328. } else {
  329. params.Customer = stripe.String(customerId)
  330. }
  331. result, err := session.New(params)
  332. if err != nil {
  333. return "", err
  334. }
  335. return result.URL, nil
  336. }
  337. func GetChargedAmount(count float64, user model.User) float64 {
  338. topUpGroupRatio := common.GetTopupGroupRatio(user.Group)
  339. if topUpGroupRatio == 0 {
  340. topUpGroupRatio = 1
  341. }
  342. return count * topUpGroupRatio
  343. }
  344. func getStripePayMoney(amount float64, group string) float64 {
  345. originalAmount := amount
  346. if operation_setting.GetQuotaDisplayType() == operation_setting.QuotaDisplayTypeTokens {
  347. amount = amount / common.QuotaPerUnit
  348. }
  349. // Using float64 for monetary calculations is acceptable here due to the small amounts involved
  350. topupGroupRatio := common.GetTopupGroupRatio(group)
  351. if topupGroupRatio == 0 {
  352. topupGroupRatio = 1
  353. }
  354. // apply optional preset discount by the original request amount (if configured), default 1.0
  355. discount := 1.0
  356. if ds, ok := operation_setting.GetPaymentSetting().AmountDiscount[int(originalAmount)]; ok {
  357. if ds > 0 {
  358. discount = ds
  359. }
  360. }
  361. payMoney := amount * setting.StripeUnitPrice * topupGroupRatio * discount
  362. return payMoney
  363. }
  364. func getStripeMinTopup() int64 {
  365. minTopup := setting.StripeMinTopUp
  366. if operation_setting.GetQuotaDisplayType() == operation_setting.QuotaDisplayTypeTokens {
  367. minTopup = minTopup * int(common.QuotaPerUnit)
  368. }
  369. return int64(minTopup)
  370. }