topup_creem.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. package controller
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "log"
  8. "net/http"
  9. "one-api/common"
  10. "one-api/model"
  11. "one-api/setting"
  12. "time"
  13. "github.com/gin-gonic/gin"
  14. "github.com/thanhpk/randstr"
  15. )
  16. const (
  17. PaymentMethodCreem = "creem"
  18. )
  19. var creemAdaptor = &CreemAdaptor{}
  20. type CreemPayRequest struct {
  21. ProductId string `json:"product_id"`
  22. PaymentMethod string `json:"payment_method"`
  23. }
  24. type CreemProduct struct {
  25. ProductId string `json:"productId"`
  26. Name string `json:"name"`
  27. Price float64 `json:"price"`
  28. Currency string `json:"currency"`
  29. Quota int64 `json:"quota"`
  30. }
  31. type CreemAdaptor struct {
  32. }
  33. func (*CreemAdaptor) RequestPay(c *gin.Context, req *CreemPayRequest) {
  34. if req.PaymentMethod != PaymentMethodCreem {
  35. c.JSON(200, gin.H{"message": "error", "data": "不支持的支付渠道"})
  36. return
  37. }
  38. if req.ProductId == "" {
  39. c.JSON(200, gin.H{"message": "error", "data": "请选择产品"})
  40. return
  41. }
  42. // 解析产品列表
  43. var products []CreemProduct
  44. err := json.Unmarshal([]byte(setting.CreemProducts), &products)
  45. if err != nil {
  46. log.Println("解析Creem产品列表失败", err)
  47. c.JSON(200, gin.H{"message": "error", "data": "产品配置错误"})
  48. return
  49. }
  50. // 查找对应的产品
  51. var selectedProduct *CreemProduct
  52. for _, product := range products {
  53. if product.ProductId == req.ProductId {
  54. selectedProduct = &product
  55. break
  56. }
  57. }
  58. if selectedProduct == nil {
  59. c.JSON(200, gin.H{"message": "error", "data": "产品不存在"})
  60. return
  61. }
  62. id := c.GetInt("id")
  63. user, _ := model.GetUserById(id, false)
  64. reference := fmt.Sprintf("creem-api-ref-%d-%d-%s", user.Id, time.Now().UnixMilli(), randstr.String(4))
  65. referenceId := "ref_" + common.Sha1([]byte(reference))
  66. checkoutUrl, err := genCreemLink(referenceId, selectedProduct, user.Email, user.Username)
  67. if err != nil {
  68. log.Println("获取Creem支付链接失败", err)
  69. c.JSON(200, gin.H{"message": "error", "data": "拉起支付失败"})
  70. return
  71. }
  72. topUp := &model.TopUp{
  73. UserId: id,
  74. Amount: selectedProduct.Quota,
  75. Money: selectedProduct.Price,
  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. "checkout_url": checkoutUrl,
  89. },
  90. })
  91. }
  92. func RequestCreemPay(c *gin.Context) {
  93. var req CreemPayRequest
  94. err := c.ShouldBindJSON(&req)
  95. if err != nil {
  96. c.JSON(200, gin.H{"message": "error", "data": "参数错误"})
  97. return
  98. }
  99. creemAdaptor.RequestPay(c, &req)
  100. }
  101. type CreemWebhookData struct {
  102. Type string `json:"type"`
  103. Data struct {
  104. RequestId string `json:"request_id"`
  105. Status string `json:"status"`
  106. Metadata map[string]string `json:"metadata"`
  107. } `json:"data"`
  108. }
  109. func CreemWebhook(c *gin.Context) {
  110. // 解析 webhook 数据
  111. var webhookData CreemWebhookData
  112. if err := c.ShouldBindJSON(&webhookData); err != nil {
  113. log.Printf("解析Creem Webhook参数失败: %v\n", err)
  114. c.AbortWithStatus(http.StatusBadRequest)
  115. return
  116. }
  117. // 检查事件类型
  118. if webhookData.Type != "checkout.completed" {
  119. log.Printf("忽略Creem Webhook事件类型: %s", webhookData.Type)
  120. c.Status(http.StatusOK)
  121. return
  122. }
  123. // 获取引用ID
  124. referenceId := webhookData.Data.RequestId
  125. if referenceId == "" {
  126. log.Println("Creem Webhook缺少request_id字段")
  127. c.AbortWithStatus(http.StatusBadRequest)
  128. return
  129. }
  130. // 处理支付完成事件
  131. err := model.RechargeCreem(referenceId)
  132. if err != nil {
  133. log.Println("Creem充值处理失败:", err.Error(), referenceId)
  134. c.AbortWithStatus(http.StatusInternalServerError)
  135. return
  136. }
  137. log.Printf("Creem充值成功: %s", referenceId)
  138. c.Status(http.StatusOK)
  139. }
  140. type CreemCheckoutRequest struct {
  141. ProductId string `json:"product_id"`
  142. RequestId string `json:"request_id"`
  143. Customer struct {
  144. Email string `json:"email"`
  145. } `json:"customer"`
  146. Metadata map[string]string `json:"metadata,omitempty"`
  147. }
  148. type CreemCheckoutResponse struct {
  149. CheckoutUrl string `json:"checkout_url"`
  150. Id string `json:"id"`
  151. }
  152. func genCreemLink(referenceId string, product *CreemProduct, email string, username string) (string, error) {
  153. if setting.CreemApiKey == "" {
  154. return "", fmt.Errorf("未配置Creem API密钥")
  155. }
  156. // 根据测试模式选择 API 端点
  157. apiUrl := "https://api.creem.io/v1/checkouts"
  158. if setting.CreemTestMode {
  159. apiUrl = "https://test-api.creem.io/v1/checkouts"
  160. }
  161. // 构建请求数据
  162. requestData := CreemCheckoutRequest{
  163. ProductId: product.ProductId,
  164. RequestId: referenceId,
  165. Customer: struct {
  166. Email string `json:"email"`
  167. }{
  168. Email: email,
  169. },
  170. Metadata: map[string]string{
  171. "username": username,
  172. "reference_id": referenceId,
  173. },
  174. }
  175. // 序列化请求数据
  176. jsonData, err := json.Marshal(requestData)
  177. if err != nil {
  178. return "", fmt.Errorf("序列化请求数据失败: %v", err)
  179. }
  180. // 创建 HTTP 请求
  181. req, err := http.NewRequest("POST", apiUrl, bytes.NewBuffer(jsonData))
  182. if err != nil {
  183. return "", fmt.Errorf("创建HTTP请求失败: %v", err)
  184. }
  185. // 设置请求头
  186. req.Header.Set("Content-Type", "application/json")
  187. req.Header.Set("x-api-key", setting.CreemApiKey)
  188. // 发送请求
  189. client := &http.Client{
  190. Timeout: 30 * time.Second,
  191. }
  192. resp, err := client.Do(req)
  193. if err != nil {
  194. return "", fmt.Errorf("发送HTTP请求失败: %v", err)
  195. }
  196. defer resp.Body.Close()
  197. log.Printf(" creem req host: %s, key %s req 【%s】", apiUrl, setting.CreemApiKey, jsonData)
  198. // 读取响应
  199. body, err := io.ReadAll(resp.Body)
  200. if err != nil {
  201. return "", fmt.Errorf("读取响应失败: %v", err)
  202. }
  203. // 检查响应状态
  204. if resp.StatusCode != http.StatusOK {
  205. return "", fmt.Errorf("Creem API 返回错误状态 %d: %s", resp.StatusCode, string(body))
  206. }
  207. // 解析响应
  208. var checkoutResp CreemCheckoutResponse
  209. err = json.Unmarshal(body, &checkoutResp)
  210. if err != nil {
  211. return "", fmt.Errorf("解析响应失败: %v", err)
  212. }
  213. if checkoutResp.CheckoutUrl == "" {
  214. return "", fmt.Errorf("Creem API 未返回支付链接")
  215. }
  216. log.Printf("Creem 支付链接创建成功: %s, 订单ID: %s", referenceId, checkoutResp.Id)
  217. return checkoutResp.CheckoutUrl, nil
  218. }