subscription_payment_stripe.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. package controller
  2. import (
  3. "fmt"
  4. "log"
  5. "net/http"
  6. "strings"
  7. "time"
  8. "github.com/QuantumNous/new-api/common"
  9. "github.com/QuantumNous/new-api/model"
  10. "github.com/QuantumNous/new-api/setting"
  11. "github.com/QuantumNous/new-api/setting/system_setting"
  12. "github.com/gin-gonic/gin"
  13. "github.com/stripe/stripe-go/v81"
  14. "github.com/stripe/stripe-go/v81/checkout/session"
  15. "github.com/thanhpk/randstr"
  16. )
  17. type SubscriptionStripePayRequest struct {
  18. PlanId int `json:"plan_id"`
  19. }
  20. func SubscriptionRequestStripePay(c *gin.Context) {
  21. var req SubscriptionStripePayRequest
  22. if err := c.ShouldBindJSON(&req); err != nil || req.PlanId <= 0 {
  23. common.ApiErrorMsg(c, "参数错误")
  24. return
  25. }
  26. plan, err := model.GetSubscriptionPlanById(req.PlanId)
  27. if err != nil {
  28. common.ApiError(c, err)
  29. return
  30. }
  31. if !plan.Enabled {
  32. common.ApiErrorMsg(c, "套餐未启用")
  33. return
  34. }
  35. if plan.StripePriceId == "" {
  36. common.ApiErrorMsg(c, "该套餐未配置 StripePriceId")
  37. return
  38. }
  39. if !strings.HasPrefix(setting.StripeApiSecret, "sk_") && !strings.HasPrefix(setting.StripeApiSecret, "rk_") {
  40. common.ApiErrorMsg(c, "Stripe 未配置或密钥无效")
  41. return
  42. }
  43. if setting.StripeWebhookSecret == "" {
  44. common.ApiErrorMsg(c, "Stripe Webhook 未配置")
  45. return
  46. }
  47. userId := c.GetInt("id")
  48. user, err := model.GetUserById(userId, false)
  49. if err != nil {
  50. common.ApiError(c, err)
  51. return
  52. }
  53. if user == nil {
  54. common.ApiErrorMsg(c, "用户不存在")
  55. return
  56. }
  57. if plan.MaxPurchasePerUser > 0 {
  58. count, err := model.CountUserSubscriptionsByPlan(userId, plan.Id)
  59. if err != nil {
  60. common.ApiError(c, err)
  61. return
  62. }
  63. if count >= int64(plan.MaxPurchasePerUser) {
  64. common.ApiErrorMsg(c, "已达到该套餐购买上限")
  65. return
  66. }
  67. }
  68. reference := fmt.Sprintf("sub-stripe-ref-%d-%d-%s", user.Id, time.Now().UnixMilli(), randstr.String(4))
  69. referenceId := "sub_ref_" + common.Sha1([]byte(reference))
  70. payLink, err := genStripeSubscriptionLink(referenceId, user.StripeCustomer, user.Email, plan.StripePriceId)
  71. if err != nil {
  72. log.Println("获取Stripe Checkout支付链接失败", err)
  73. c.JSON(http.StatusOK, gin.H{"message": "error", "data": "拉起支付失败"})
  74. return
  75. }
  76. order := &model.SubscriptionOrder{
  77. UserId: userId,
  78. PlanId: plan.Id,
  79. Money: plan.PriceAmount,
  80. TradeNo: referenceId,
  81. PaymentMethod: PaymentMethodStripe,
  82. CreateTime: time.Now().Unix(),
  83. Status: common.TopUpStatusPending,
  84. }
  85. if err := order.Insert(); err != nil {
  86. c.JSON(http.StatusOK, gin.H{"message": "error", "data": "创建订单失败"})
  87. return
  88. }
  89. c.JSON(http.StatusOK, gin.H{
  90. "message": "success",
  91. "data": gin.H{
  92. "pay_link": payLink,
  93. },
  94. })
  95. }
  96. func genStripeSubscriptionLink(referenceId string, customerId string, email string, priceId string) (string, error) {
  97. stripe.Key = setting.StripeApiSecret
  98. params := &stripe.CheckoutSessionParams{
  99. ClientReferenceID: stripe.String(referenceId),
  100. SuccessURL: stripe.String(system_setting.ServerAddress + "/console/topup"),
  101. CancelURL: stripe.String(system_setting.ServerAddress + "/console/topup"),
  102. LineItems: []*stripe.CheckoutSessionLineItemParams{
  103. {
  104. Price: stripe.String(priceId),
  105. Quantity: stripe.Int64(1),
  106. },
  107. },
  108. Mode: stripe.String(string(stripe.CheckoutSessionModeSubscription)),
  109. }
  110. if "" == customerId {
  111. if "" != email {
  112. params.CustomerEmail = stripe.String(email)
  113. }
  114. params.CustomerCreation = stripe.String(string(stripe.CheckoutSessionCustomerCreationAlways))
  115. } else {
  116. params.Customer = stripe.String(customerId)
  117. }
  118. result, err := session.New(params)
  119. if err != nil {
  120. return "", err
  121. }
  122. return result.URL, nil
  123. }