Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 

362 Zeilen
11 KiB

  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. PaymentProvider: model.PaymentProviderStripe,
  98. CreateTime: time.Now().Unix(),
  99. Status: common.TopUpStatusPending,
  100. }
  101. err = topUp.Insert()
  102. if err != nil {
  103. c.JSON(200, gin.H{"message": "error", "data": "创建订单失败"})
  104. return
  105. }
  106. c.JSON(200, 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(200, 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(200, gin.H{"message": "error", "data": "参数错误"})
  127. return
  128. }
  129. stripeAdaptor.RequestPay(c, &req)
  130. }
  131. func StripeWebhook(c *gin.Context) {
  132. if !isStripeWebhookEnabled() {
  133. log.Printf("Stripe webhook 被拒绝: webhook 未配置或已禁用 (client_ip=%s)\n", c.ClientIP())
  134. c.AbortWithStatus(http.StatusForbidden)
  135. return
  136. }
  137. payload, err := io.ReadAll(c.Request.Body)
  138. if err != nil {
  139. log.Printf("解析Stripe Webhook参数失败: %v\n", err)
  140. c.AbortWithStatus(http.StatusServiceUnavailable)
  141. return
  142. }
  143. signature := c.GetHeader("Stripe-Signature")
  144. endpointSecret := setting.StripeWebhookSecret
  145. event, err := webhook.ConstructEventWithOptions(payload, signature, endpointSecret, webhook.ConstructEventOptions{
  146. IgnoreAPIVersionMismatch: true,
  147. })
  148. if err != nil {
  149. log.Printf("Stripe Webhook验签失败: %v\n", err)
  150. c.AbortWithStatus(http.StatusBadRequest)
  151. return
  152. }
  153. switch event.Type {
  154. case stripe.EventTypeCheckoutSessionCompleted:
  155. sessionCompleted(event)
  156. case stripe.EventTypeCheckoutSessionExpired:
  157. sessionExpired(event)
  158. default:
  159. log.Printf("不支持的Stripe Webhook事件类型: %s\n", event.Type)
  160. }
  161. c.Status(http.StatusOK)
  162. }
  163. func sessionCompleted(event stripe.Event) {
  164. customerId := event.GetObjectValue("customer")
  165. referenceId := event.GetObjectValue("client_reference_id")
  166. status := event.GetObjectValue("status")
  167. if "complete" != status {
  168. log.Println("错误的Stripe Checkout完成状态:", status, ",", referenceId)
  169. return
  170. }
  171. // Try complete subscription order first
  172. LockOrder(referenceId)
  173. defer UnlockOrder(referenceId)
  174. payload := map[string]any{
  175. "customer": customerId,
  176. "amount_total": event.GetObjectValue("amount_total"),
  177. "currency": strings.ToUpper(event.GetObjectValue("currency")),
  178. "event_type": string(event.Type),
  179. }
  180. if err := model.CompleteSubscriptionOrder(referenceId, common.GetJsonString(payload)); err == nil {
  181. return
  182. } else if err != nil && !errors.Is(err, model.ErrSubscriptionOrderNotFound) {
  183. log.Println("complete subscription order failed:", err.Error(), referenceId)
  184. return
  185. }
  186. err := model.Recharge(referenceId, customerId)
  187. if err != nil {
  188. log.Println(err.Error(), referenceId)
  189. return
  190. }
  191. total, _ := strconv.ParseFloat(event.GetObjectValue("amount_total"), 64)
  192. currency := strings.ToUpper(event.GetObjectValue("currency"))
  193. log.Printf("收到款项:%s, %.2f(%s)", referenceId, total/100, currency)
  194. }
  195. func sessionExpired(event stripe.Event) {
  196. referenceId := event.GetObjectValue("client_reference_id")
  197. status := event.GetObjectValue("status")
  198. if "expired" != status {
  199. log.Println("错误的Stripe Checkout过期状态:", status, ",", referenceId)
  200. return
  201. }
  202. if len(referenceId) == 0 {
  203. log.Println("未提供支付单号")
  204. return
  205. }
  206. // Subscription order expiration
  207. LockOrder(referenceId)
  208. defer UnlockOrder(referenceId)
  209. if err := model.ExpireSubscriptionOrder(referenceId); err == nil {
  210. return
  211. } else if err != nil && !errors.Is(err, model.ErrSubscriptionOrderNotFound) {
  212. log.Println("过期订阅订单失败", referenceId, ", err:", err.Error())
  213. return
  214. }
  215. topUp := model.GetTopUpByTradeNo(referenceId)
  216. if topUp == nil {
  217. log.Println("充值订单不存在", referenceId)
  218. return
  219. }
  220. if topUp.Status != common.TopUpStatusPending {
  221. log.Println("充值订单状态错误", referenceId)
  222. }
  223. topUp.Status = common.TopUpStatusExpired
  224. err := topUp.Update()
  225. if err != nil {
  226. log.Println("过期充值订单失败", referenceId, ", err:", err.Error())
  227. return
  228. }
  229. log.Println("充值订单已过期", referenceId)
  230. }
  231. // genStripeLink generates a Stripe Checkout session URL for payment.
  232. // It creates a new checkout session with the specified parameters and returns the payment URL.
  233. //
  234. // Parameters:
  235. // - referenceId: unique reference identifier for the transaction
  236. // - customerId: existing Stripe customer ID (empty string if new customer)
  237. // - email: customer email address for new customer creation
  238. // - amount: quantity of units to purchase
  239. // - successURL: custom URL to redirect after successful payment (empty for default)
  240. // - cancelURL: custom URL to redirect when payment is canceled (empty for default)
  241. //
  242. // Returns the checkout session URL or an error if the session creation fails.
  243. func genStripeLink(referenceId string, customerId string, email string, amount int64, successURL string, cancelURL string) (string, error) {
  244. if !strings.HasPrefix(setting.StripeApiSecret, "sk_") && !strings.HasPrefix(setting.StripeApiSecret, "rk_") {
  245. return "", fmt.Errorf("无效的Stripe API密钥")
  246. }
  247. stripe.Key = setting.StripeApiSecret
  248. // Use custom URLs if provided, otherwise use defaults
  249. if successURL == "" {
  250. successURL = system_setting.ServerAddress + "/console/log"
  251. }
  252. if cancelURL == "" {
  253. cancelURL = system_setting.ServerAddress + "/console/topup"
  254. }
  255. params := &stripe.CheckoutSessionParams{
  256. ClientReferenceID: stripe.String(referenceId),
  257. SuccessURL: stripe.String(successURL),
  258. CancelURL: stripe.String(cancelURL),
  259. LineItems: []*stripe.CheckoutSessionLineItemParams{
  260. {
  261. Price: stripe.String(setting.StripePriceId),
  262. Quantity: stripe.Int64(amount),
  263. },
  264. },
  265. Mode: stripe.String(string(stripe.CheckoutSessionModePayment)),
  266. AllowPromotionCodes: stripe.Bool(setting.StripePromotionCodesEnabled),
  267. }
  268. if "" == customerId {
  269. if "" != email {
  270. params.CustomerEmail = stripe.String(email)
  271. }
  272. params.CustomerCreation = stripe.String(string(stripe.CheckoutSessionCustomerCreationAlways))
  273. } else {
  274. params.Customer = stripe.String(customerId)
  275. }
  276. result, err := session.New(params)
  277. if err != nil {
  278. return "", err
  279. }
  280. return result.URL, nil
  281. }
  282. func GetChargedAmount(count float64, user model.User) float64 {
  283. topUpGroupRatio := common.GetTopupGroupRatio(user.Group)
  284. if topUpGroupRatio == 0 {
  285. topUpGroupRatio = 1
  286. }
  287. return count * topUpGroupRatio
  288. }
  289. func getStripePayMoney(amount float64, group string) float64 {
  290. originalAmount := amount
  291. if operation_setting.GetQuotaDisplayType() == operation_setting.QuotaDisplayTypeTokens {
  292. amount = amount / common.QuotaPerUnit
  293. }
  294. // Using float64 for monetary calculations is acceptable here due to the small amounts involved
  295. topupGroupRatio := common.GetTopupGroupRatio(group)
  296. if topupGroupRatio == 0 {
  297. topupGroupRatio = 1
  298. }
  299. // apply optional preset discount by the original request amount (if configured), default 1.0
  300. discount := 1.0
  301. if ds, ok := operation_setting.GetPaymentSetting().AmountDiscount[int(originalAmount)]; ok {
  302. if ds > 0 {
  303. discount = ds
  304. }
  305. }
  306. payMoney := amount * setting.StripeUnitPrice * topupGroupRatio * discount
  307. return payMoney
  308. }
  309. func getStripeMinTopup() int64 {
  310. minTopup := setting.StripeMinTopUp
  311. if operation_setting.GetQuotaDisplayType() == operation_setting.QuotaDisplayTypeTokens {
  312. minTopup = minTopup * int(common.QuotaPerUnit)
  313. }
  314. return int64(minTopup)
  315. }