topup_stripe.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. package controller
  2. import (
  3. "fmt"
  4. "io"
  5. "log"
  6. "net/http"
  7. "one-api/common"
  8. "one-api/model"
  9. "one-api/setting"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "github.com/gin-gonic/gin"
  14. "github.com/stripe/stripe-go/v81"
  15. "github.com/stripe/stripe-go/v81/checkout/session"
  16. "github.com/stripe/stripe-go/v81/webhook"
  17. "github.com/thanhpk/randstr"
  18. )
  19. const (
  20. PaymentMethodStripe = "stripe"
  21. )
  22. var stripeAdaptor = &StripeAdaptor{}
  23. type StripePayRequest struct {
  24. Amount int64 `json:"amount"`
  25. PaymentMethod string `json:"payment_method"`
  26. TopUpCode string `json:"top_up_code"`
  27. }
  28. type StripeAdaptor struct {
  29. }
  30. func (*StripeAdaptor) RequestAmount(c *gin.Context, req *StripePayRequest) {
  31. if req.Amount < getStripeMinTopup() {
  32. c.JSON(200, gin.H{"message": "error", "data": fmt.Sprintf("充值数量不能小于 %d", getStripeMinTopup())})
  33. return
  34. }
  35. id := c.GetInt("id")
  36. group, err := model.GetUserGroup(id, true)
  37. if err != nil {
  38. c.JSON(200, gin.H{"message": "error", "data": "获取用户分组失败"})
  39. return
  40. }
  41. payMoney := getStripePayMoney(float64(req.Amount), group)
  42. if payMoney <= 0.01 {
  43. c.JSON(200, gin.H{"message": "error", "data": "充值金额过低"})
  44. return
  45. }
  46. c.JSON(200, gin.H{"message": "success", "data": strconv.FormatFloat(payMoney, 'f', 2, 64)})
  47. }
  48. func (*StripeAdaptor) RequestPay(c *gin.Context, req *StripePayRequest) {
  49. if req.PaymentMethod != PaymentMethodStripe {
  50. c.JSON(200, gin.H{"message": "error", "data": "不支持的支付渠道"})
  51. return
  52. }
  53. if req.Amount < int64(setting.StripeMinTopUp) {
  54. c.JSON(200, gin.H{"message": fmt.Sprintf("充值数量不能小于 %d", setting.StripeMinTopUp), "data": 10})
  55. return
  56. }
  57. if req.Amount > 10000 {
  58. c.JSON(200, gin.H{"message": "充值数量不能大于 10000", "data": 10})
  59. return
  60. }
  61. id := c.GetInt("id")
  62. user, _ := model.GetUserById(id, false)
  63. chargedMoney := GetChargedAmount(float64(req.Amount), *user)
  64. reference := fmt.Sprintf("new-api-ref-%d-%d-%s", user.Id, time.Now().UnixMilli(), randstr.String(4))
  65. referenceId := "ref_" + common.Sha1(reference)
  66. payLink, err := genStripeLink(referenceId, user.StripeCustomer, user.Email, req.Amount)
  67. if err != nil {
  68. log.Println("获取Stripe Checkout支付链接失败", err)
  69. c.JSON(200, gin.H{"message": "error", "data": "拉起支付失败"})
  70. return
  71. }
  72. topUp := &model.TopUp{
  73. UserId: id,
  74. Amount: req.Amount,
  75. Money: chargedMoney,
  76. TradeNo: referenceId,
  77. CreateTime: time.Now().Unix(),
  78. Status: common.TopUpStatusPending,
  79. }
  80. err = topUp.Insert()
  81. if err != nil {
  82. c.JSON(200, gin.H{"message": "error", "data": "创建订单失败"})
  83. return
  84. }
  85. c.JSON(200, gin.H{
  86. "message": "success",
  87. "data": gin.H{
  88. "pay_link": payLink,
  89. },
  90. })
  91. }
  92. func RequestStripeAmount(c *gin.Context) {
  93. var req StripePayRequest
  94. err := c.ShouldBindJSON(&req)
  95. if err != nil {
  96. c.JSON(200, gin.H{"message": "error", "data": "参数错误"})
  97. return
  98. }
  99. stripeAdaptor.RequestAmount(c, &req)
  100. }
  101. func RequestStripePay(c *gin.Context) {
  102. var req StripePayRequest
  103. err := c.ShouldBindJSON(&req)
  104. if err != nil {
  105. c.JSON(200, gin.H{"message": "error", "data": "参数错误"})
  106. return
  107. }
  108. stripeAdaptor.RequestPay(c, &req)
  109. }
  110. func StripeWebhook(c *gin.Context) {
  111. payload, err := io.ReadAll(c.Request.Body)
  112. if err != nil {
  113. log.Printf("解析Stripe Webhook参数失败: %v\n", err)
  114. c.AbortWithStatus(http.StatusServiceUnavailable)
  115. return
  116. }
  117. signature := c.GetHeader("Stripe-Signature")
  118. endpointSecret := setting.StripeWebhookSecret
  119. event, err := webhook.ConstructEventWithOptions(payload, signature, endpointSecret, webhook.ConstructEventOptions{
  120. IgnoreAPIVersionMismatch: true,
  121. })
  122. if err != nil {
  123. log.Printf("Stripe Webhook验签失败: %v\n", err)
  124. c.AbortWithStatus(http.StatusBadRequest)
  125. return
  126. }
  127. switch event.Type {
  128. case stripe.EventTypeCheckoutSessionCompleted:
  129. sessionCompleted(event)
  130. case stripe.EventTypeCheckoutSessionExpired:
  131. sessionExpired(event)
  132. default:
  133. log.Printf("不支持的Stripe Webhook事件类型: %s\n", event.Type)
  134. }
  135. c.Status(http.StatusOK)
  136. }
  137. func sessionCompleted(event stripe.Event) {
  138. customerId := event.GetObjectValue("customer")
  139. referenceId := event.GetObjectValue("client_reference_id")
  140. status := event.GetObjectValue("status")
  141. if "complete" != status {
  142. log.Println("错误的Stripe Checkout完成状态:", status, ",", referenceId)
  143. return
  144. }
  145. err := model.Recharge(referenceId, customerId)
  146. if err != nil {
  147. log.Println(err.Error(), referenceId)
  148. return
  149. }
  150. total, _ := strconv.ParseFloat(event.GetObjectValue("amount_total"), 64)
  151. currency := strings.ToUpper(event.GetObjectValue("currency"))
  152. log.Printf("收到款项:%s, %.2f(%s)", referenceId, total/100, currency)
  153. }
  154. func sessionExpired(event stripe.Event) {
  155. referenceId := event.GetObjectValue("client_reference_id")
  156. status := event.GetObjectValue("status")
  157. if "expired" != status {
  158. log.Println("错误的Stripe Checkout过期状态:", status, ",", referenceId)
  159. return
  160. }
  161. if "" == referenceId {
  162. log.Println("未提供支付单号")
  163. return
  164. }
  165. topUp := model.GetTopUpByTradeNo(referenceId)
  166. if topUp == nil {
  167. log.Println("充值订单不存在", referenceId)
  168. return
  169. }
  170. if topUp.Status != common.TopUpStatusPending {
  171. log.Println("充值订单状态错误", referenceId)
  172. }
  173. topUp.Status = common.TopUpStatusExpired
  174. err := topUp.Update()
  175. if err != nil {
  176. log.Println("过期充值订单失败", referenceId, ", err:", err.Error())
  177. return
  178. }
  179. log.Println("充值订单已过期", referenceId)
  180. }
  181. func genStripeLink(referenceId string, customerId string, email string, amount int64) (string, error) {
  182. if !strings.HasPrefix(setting.StripeApiSecret, "sk_") && !strings.HasPrefix(setting.StripeApiSecret, "rk_") {
  183. return "", fmt.Errorf("无效的Stripe API密钥")
  184. }
  185. stripe.Key = setting.StripeApiSecret
  186. params := &stripe.CheckoutSessionParams{
  187. ClientReferenceID: stripe.String(referenceId),
  188. SuccessURL: stripe.String(setting.ServerAddress + "/log"),
  189. CancelURL: stripe.String(setting.ServerAddress + "/topup"),
  190. LineItems: []*stripe.CheckoutSessionLineItemParams{
  191. {
  192. Price: stripe.String(setting.StripePriceId),
  193. Quantity: stripe.Int64(amount),
  194. },
  195. },
  196. Mode: stripe.String(string(stripe.CheckoutSessionModePayment)),
  197. }
  198. if "" == customerId {
  199. if "" != email {
  200. params.CustomerEmail = stripe.String(email)
  201. }
  202. params.CustomerCreation = stripe.String(string(stripe.CheckoutSessionCustomerCreationAlways))
  203. } else {
  204. params.Customer = stripe.String(customerId)
  205. }
  206. result, err := session.New(params)
  207. if err != nil {
  208. return "", err
  209. }
  210. return result.URL, nil
  211. }
  212. func GetChargedAmount(count float64, user model.User) float64 {
  213. topUpGroupRatio := common.GetTopupGroupRatio(user.Group)
  214. if topUpGroupRatio == 0 {
  215. topUpGroupRatio = 1
  216. }
  217. return count * topUpGroupRatio
  218. }
  219. func getStripePayMoney(amount float64, group string) float64 {
  220. if !common.DisplayInCurrencyEnabled {
  221. amount = amount / common.QuotaPerUnit
  222. }
  223. // 别问为什么用float64,问就是这么点钱没必要
  224. topupGroupRatio := common.GetTopupGroupRatio(group)
  225. if topupGroupRatio == 0 {
  226. topupGroupRatio = 1
  227. }
  228. payMoney := amount * setting.StripeUnitPrice * topupGroupRatio
  229. return payMoney
  230. }
  231. func getStripeMinTopup() int64 {
  232. minTopup := setting.StripeMinTopUp
  233. if !common.DisplayInCurrencyEnabled {
  234. minTopup = minTopup * int(common.QuotaPerUnit)
  235. }
  236. return int64(minTopup)
  237. }