topup_stripe.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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. CreateTime: time.Now().Unix(),
  96. Status: common.TopUpStatusPending,
  97. }
  98. err = topUp.Insert()
  99. if err != nil {
  100. logger.LogError(c.Request.Context(), fmt.Sprintf("Stripe 创建充值订单失败 user_id=%d trade_no=%s amount=%d error=%q", id, referenceId, req.Amount, err.Error()))
  101. c.JSON(http.StatusOK, gin.H{"message": "error", "data": "创建订单失败"})
  102. return
  103. }
  104. logger.LogInfo(c.Request.Context(), fmt.Sprintf("Stripe 充值订单创建成功 user_id=%d trade_no=%s amount=%d money=%.2f", id, referenceId, req.Amount, chargedMoney))
  105. c.JSON(http.StatusOK, 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(http.StatusOK, 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(http.StatusOK, gin.H{"message": "error", "data": "参数错误"})
  126. return
  127. }
  128. stripeAdaptor.RequestPay(c, &req)
  129. }
  130. func StripeWebhook(c *gin.Context) {
  131. ctx := c.Request.Context()
  132. if !isStripeWebhookEnabled() {
  133. logger.LogWarn(ctx, fmt.Sprintf("Stripe webhook 被拒绝 reason=webhook_disabled path=%q client_ip=%s", c.Request.RequestURI, c.ClientIP()))
  134. c.AbortWithStatus(http.StatusForbidden)
  135. return
  136. }
  137. payload, err := io.ReadAll(c.Request.Body)
  138. if err != nil {
  139. logger.LogError(ctx, fmt.Sprintf("Stripe webhook 读取请求体失败 path=%q client_ip=%s error=%q", c.Request.RequestURI, c.ClientIP(), err.Error()))
  140. c.AbortWithStatus(http.StatusServiceUnavailable)
  141. return
  142. }
  143. signature := c.GetHeader("Stripe-Signature")
  144. logger.LogInfo(ctx, fmt.Sprintf("Stripe webhook 收到请求 path=%q client_ip=%s signature=%q body=%q", c.Request.RequestURI, c.ClientIP(), signature, string(payload)))
  145. event, err := webhook.ConstructEventWithOptions(payload, signature, setting.StripeWebhookSecret, webhook.ConstructEventOptions{
  146. IgnoreAPIVersionMismatch: true,
  147. })
  148. if err != nil {
  149. logger.LogWarn(ctx, fmt.Sprintf("Stripe webhook 验签失败 path=%q client_ip=%s error=%q", c.Request.RequestURI, c.ClientIP(), err.Error()))
  150. c.AbortWithStatus(http.StatusBadRequest)
  151. return
  152. }
  153. callerIp := c.ClientIP()
  154. logger.LogInfo(ctx, fmt.Sprintf("Stripe webhook 验签成功 event_type=%s client_ip=%s path=%q", string(event.Type), callerIp, c.Request.RequestURI))
  155. switch event.Type {
  156. case stripe.EventTypeCheckoutSessionCompleted:
  157. sessionCompleted(ctx, event, callerIp)
  158. case stripe.EventTypeCheckoutSessionExpired:
  159. sessionExpired(ctx, event)
  160. case stripe.EventTypeCheckoutSessionAsyncPaymentSucceeded:
  161. sessionAsyncPaymentSucceeded(ctx, event, callerIp)
  162. case stripe.EventTypeCheckoutSessionAsyncPaymentFailed:
  163. sessionAsyncPaymentFailed(ctx, event, callerIp)
  164. default:
  165. logger.LogInfo(ctx, fmt.Sprintf("Stripe webhook 忽略事件 event_type=%s client_ip=%s", string(event.Type), callerIp))
  166. }
  167. c.Status(http.StatusOK)
  168. }
  169. func sessionCompleted(ctx context.Context, event stripe.Event, callerIp string) {
  170. customerId := event.GetObjectValue("customer")
  171. referenceId := event.GetObjectValue("client_reference_id")
  172. status := event.GetObjectValue("status")
  173. if "complete" != status {
  174. logger.LogWarn(ctx, fmt.Sprintf("Stripe checkout.completed 状态异常,忽略处理 trade_no=%s status=%s client_ip=%s", referenceId, status, callerIp))
  175. return
  176. }
  177. paymentStatus := event.GetObjectValue("payment_status")
  178. if paymentStatus != "paid" {
  179. logger.LogInfo(ctx, fmt.Sprintf("Stripe Checkout 支付未完成,等待异步结果 trade_no=%s payment_status=%s client_ip=%s", referenceId, paymentStatus, callerIp))
  180. return
  181. }
  182. fulfillOrder(ctx, event, referenceId, customerId, callerIp)
  183. }
  184. // sessionAsyncPaymentSucceeded handles delayed payment methods (bank transfer, SEPA, etc.)
  185. // that confirm payment after the checkout session completes.
  186. func sessionAsyncPaymentSucceeded(ctx context.Context, event stripe.Event, callerIp string) {
  187. customerId := event.GetObjectValue("customer")
  188. referenceId := event.GetObjectValue("client_reference_id")
  189. logger.LogInfo(ctx, fmt.Sprintf("Stripe 异步支付成功 trade_no=%s client_ip=%s", referenceId, callerIp))
  190. fulfillOrder(ctx, event, referenceId, customerId, callerIp)
  191. }
  192. // sessionAsyncPaymentFailed marks orders as failed when delayed payment methods
  193. // ultimately fail (e.g. bank transfer not received, SEPA rejected).
  194. func sessionAsyncPaymentFailed(ctx context.Context, event stripe.Event, callerIp string) {
  195. referenceId := event.GetObjectValue("client_reference_id")
  196. logger.LogWarn(ctx, fmt.Sprintf("Stripe 异步支付失败 trade_no=%s client_ip=%s", referenceId, callerIp))
  197. if len(referenceId) == 0 {
  198. logger.LogWarn(ctx, fmt.Sprintf("Stripe 异步支付失败事件缺少订单号 client_ip=%s", callerIp))
  199. return
  200. }
  201. LockOrder(referenceId)
  202. defer UnlockOrder(referenceId)
  203. topUp := model.GetTopUpByTradeNo(referenceId)
  204. if topUp == nil {
  205. logger.LogWarn(ctx, fmt.Sprintf("Stripe 异步支付失败但本地订单不存在 trade_no=%s client_ip=%s", referenceId, callerIp))
  206. return
  207. }
  208. if topUp.PaymentMethod != model.PaymentMethodStripe {
  209. logger.LogWarn(ctx, fmt.Sprintf("Stripe 异步支付失败但订单支付方式不匹配 trade_no=%s payment_method=%s client_ip=%s", referenceId, topUp.PaymentMethod, callerIp))
  210. return
  211. }
  212. if topUp.Status != common.TopUpStatusPending {
  213. logger.LogInfo(ctx, fmt.Sprintf("Stripe 异步支付失败但订单状态非 pending,忽略处理 trade_no=%s status=%s client_ip=%s", referenceId, topUp.Status, callerIp))
  214. return
  215. }
  216. topUp.Status = common.TopUpStatusFailed
  217. if err := topUp.Update(); err != nil {
  218. logger.LogError(ctx, fmt.Sprintf("Stripe 标记充值订单失败状态失败 trade_no=%s client_ip=%s error=%q", referenceId, callerIp, err.Error()))
  219. return
  220. }
  221. logger.LogInfo(ctx, fmt.Sprintf("Stripe 充值订单已标记为失败 trade_no=%s client_ip=%s", referenceId, callerIp))
  222. }
  223. // fulfillOrder is the shared logic for crediting quota after payment is confirmed.
  224. func fulfillOrder(ctx context.Context, event stripe.Event, referenceId string, customerId string, callerIp string) {
  225. if len(referenceId) == 0 {
  226. logger.LogWarn(ctx, fmt.Sprintf("Stripe 完成订单时缺少订单号 client_ip=%s", callerIp))
  227. return
  228. }
  229. LockOrder(referenceId)
  230. defer UnlockOrder(referenceId)
  231. payload := map[string]any{
  232. "customer": customerId,
  233. "amount_total": event.GetObjectValue("amount_total"),
  234. "currency": strings.ToUpper(event.GetObjectValue("currency")),
  235. "event_type": string(event.Type),
  236. }
  237. if err := model.CompleteSubscriptionOrder(referenceId, common.GetJsonString(payload), model.PaymentMethodStripe); err == nil {
  238. logger.LogInfo(ctx, fmt.Sprintf("Stripe 订阅订单处理成功 trade_no=%s event_type=%s client_ip=%s", referenceId, string(event.Type), callerIp))
  239. return
  240. } else if err != nil && !errors.Is(err, model.ErrSubscriptionOrderNotFound) {
  241. logger.LogError(ctx, fmt.Sprintf("Stripe 订阅订单处理失败 trade_no=%s event_type=%s client_ip=%s error=%q", referenceId, string(event.Type), callerIp, err.Error()))
  242. return
  243. }
  244. err := model.Recharge(referenceId, customerId, callerIp)
  245. if err != nil {
  246. logger.LogError(ctx, fmt.Sprintf("Stripe 充值处理失败 trade_no=%s event_type=%s client_ip=%s error=%q", referenceId, string(event.Type), callerIp, err.Error()))
  247. return
  248. }
  249. total, _ := strconv.ParseFloat(event.GetObjectValue("amount_total"), 64)
  250. currency := strings.ToUpper(event.GetObjectValue("currency"))
  251. 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))
  252. }
  253. func sessionExpired(ctx context.Context, event stripe.Event) {
  254. referenceId := event.GetObjectValue("client_reference_id")
  255. status := event.GetObjectValue("status")
  256. if "expired" != status {
  257. logger.LogWarn(ctx, fmt.Sprintf("Stripe checkout.expired 状态异常,忽略处理 trade_no=%s status=%s", referenceId, status))
  258. return
  259. }
  260. if len(referenceId) == 0 {
  261. logger.LogWarn(ctx, "Stripe checkout.expired 缺少订单号")
  262. return
  263. }
  264. // Subscription order expiration
  265. LockOrder(referenceId)
  266. defer UnlockOrder(referenceId)
  267. if err := model.ExpireSubscriptionOrder(referenceId, model.PaymentMethodStripe); err == nil {
  268. logger.LogInfo(ctx, fmt.Sprintf("Stripe 订阅订单已过期 trade_no=%s", referenceId))
  269. return
  270. } else if err != nil && !errors.Is(err, model.ErrSubscriptionOrderNotFound) {
  271. logger.LogError(ctx, fmt.Sprintf("Stripe 订阅订单过期处理失败 trade_no=%s error=%q", referenceId, err.Error()))
  272. return
  273. }
  274. err := model.UpdatePendingTopUpStatus(referenceId, model.PaymentMethodStripe, common.TopUpStatusExpired)
  275. if errors.Is(err, model.ErrTopUpNotFound) {
  276. logger.LogWarn(ctx, fmt.Sprintf("Stripe 充值订单不存在,无法标记过期 trade_no=%s", referenceId))
  277. return
  278. }
  279. if err != nil {
  280. logger.LogError(ctx, fmt.Sprintf("Stripe 充值订单过期处理失败 trade_no=%s error=%q", referenceId, err.Error()))
  281. return
  282. }
  283. logger.LogInfo(ctx, fmt.Sprintf("Stripe 充值订单已过期 trade_no=%s", 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. }