topup_creem.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. package controller
  2. import (
  3. "bytes"
  4. "crypto/hmac"
  5. "crypto/sha256"
  6. "encoding/hex"
  7. "encoding/json"
  8. "fmt"
  9. "io"
  10. "log"
  11. "net/http"
  12. "one-api/common"
  13. "one-api/model"
  14. "one-api/setting"
  15. "time"
  16. "github.com/gin-gonic/gin"
  17. "github.com/thanhpk/randstr"
  18. )
  19. const (
  20. PaymentMethodCreem = "creem"
  21. CreemSignatureHeader = "creem-signature"
  22. )
  23. var creemAdaptor = &CreemAdaptor{}
  24. // 生成HMAC-SHA256签名
  25. func generateCreemSignature(payload string, secret string) string {
  26. h := hmac.New(sha256.New, []byte(secret))
  27. h.Write([]byte(payload))
  28. return hex.EncodeToString(h.Sum(nil))
  29. }
  30. // 验证Creem webhook签名
  31. func verifyCreemSignature(payload string, signature string, secret string) bool {
  32. if secret == "" {
  33. log.Printf("Creem webhook secret未配置,跳过签名验证")
  34. return true // 如果没有配置secret,跳过验证
  35. }
  36. expectedSignature := generateCreemSignature(payload, secret)
  37. return hmac.Equal([]byte(signature), []byte(expectedSignature))
  38. }
  39. type CreemPayRequest struct {
  40. ProductId string `json:"product_id"`
  41. PaymentMethod string `json:"payment_method"`
  42. }
  43. type CreemProduct struct {
  44. ProductId string `json:"productId"`
  45. Name string `json:"name"`
  46. Price float64 `json:"price"`
  47. Currency string `json:"currency"`
  48. Quota int64 `json:"quota"`
  49. }
  50. type CreemAdaptor struct {
  51. }
  52. func (*CreemAdaptor) RequestPay(c *gin.Context, req *CreemPayRequest) {
  53. if req.PaymentMethod != PaymentMethodCreem {
  54. c.JSON(200, gin.H{"message": "error", "data": "不支持的支付渠道"})
  55. return
  56. }
  57. if req.ProductId == "" {
  58. c.JSON(200, gin.H{"message": "error", "data": "请选择产品"})
  59. return
  60. }
  61. // 解析产品列表
  62. var products []CreemProduct
  63. err := json.Unmarshal([]byte(setting.CreemProducts), &products)
  64. if err != nil {
  65. log.Println("解析Creem产品列表失败", err)
  66. c.JSON(200, gin.H{"message": "error", "data": "产品配置错误"})
  67. return
  68. }
  69. // 查找对应的产品
  70. var selectedProduct *CreemProduct
  71. for _, product := range products {
  72. if product.ProductId == req.ProductId {
  73. selectedProduct = &product
  74. break
  75. }
  76. }
  77. if selectedProduct == nil {
  78. c.JSON(200, gin.H{"message": "error", "data": "产品不存在"})
  79. return
  80. }
  81. id := c.GetInt("id")
  82. user, _ := model.GetUserById(id, false)
  83. // 生成唯一的订单引用ID
  84. reference := fmt.Sprintf("creem-api-ref-%d-%d-%s", user.Id, time.Now().UnixMilli(), randstr.String(4))
  85. referenceId := "ref_" + common.Sha1([]byte(reference))
  86. // 先创建订单记录,使用产品配置的金额和充值额度
  87. topUp := &model.TopUp{
  88. UserId: id,
  89. Amount: selectedProduct.Quota, // 充值额度
  90. Money: selectedProduct.Price, // 支付金额
  91. TradeNo: referenceId,
  92. CreateTime: time.Now().Unix(),
  93. Status: common.TopUpStatusPending,
  94. }
  95. err = topUp.Insert()
  96. if err != nil {
  97. log.Printf("创建Creem订单失败: %v", err)
  98. c.JSON(200, gin.H{"message": "error", "data": "创建订单失败"})
  99. return
  100. }
  101. // 创建支付链接,传入用户邮箱
  102. checkoutUrl, err := genCreemLink(referenceId, selectedProduct, user.Email, user.Username)
  103. if err != nil {
  104. log.Printf("获取Creem支付链接失败: %v", err)
  105. c.JSON(200, gin.H{"message": "error", "data": "拉起支付失败"})
  106. return
  107. }
  108. log.Printf("Creem订单创建成功 - 用户ID: %d, 订单号: %s, 产品: %s, 充值额度: %d, 支付金额: %.2f",
  109. id, referenceId, selectedProduct.Name, selectedProduct.Quota, selectedProduct.Price)
  110. c.JSON(200, gin.H{
  111. "message": "success",
  112. "data": gin.H{
  113. "checkout_url": checkoutUrl,
  114. "order_id": referenceId,
  115. },
  116. })
  117. }
  118. func RequestCreemPay(c *gin.Context) {
  119. var req CreemPayRequest
  120. // 读取body内容用于打印,同时保留原始数据供后续使用
  121. bodyBytes, err := io.ReadAll(c.Request.Body)
  122. if err != nil {
  123. log.Printf("读取请求body失败: %v", err)
  124. c.JSON(200, gin.H{"message": "error", "data": "读取请求失败"})
  125. return
  126. }
  127. // 打印body内容
  128. log.Printf("creem pay request body: %s", string(bodyBytes))
  129. // 重新设置body供后续的ShouldBindJSON使用
  130. c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes))
  131. err = c.ShouldBindJSON(&req)
  132. log.Printf(" json body is %+v", req)
  133. if err != nil {
  134. c.JSON(200, gin.H{"message": "error", "data": "参数错误"})
  135. return
  136. }
  137. creemAdaptor.RequestPay(c, &req)
  138. }
  139. // 新的Creem Webhook结构体,匹配实际的webhook数据格式
  140. type CreemWebhookEvent struct {
  141. Id string `json:"id"`
  142. EventType string `json:"eventType"`
  143. CreatedAt int64 `json:"created_at"`
  144. Object struct {
  145. Id string `json:"id"`
  146. Object string `json:"object"`
  147. RequestId string `json:"request_id"`
  148. Order struct {
  149. Object string `json:"object"`
  150. Id string `json:"id"`
  151. Customer string `json:"customer"`
  152. Product string `json:"product"`
  153. Amount int `json:"amount"`
  154. Currency string `json:"currency"`
  155. SubTotal int `json:"sub_total"`
  156. TaxAmount int `json:"tax_amount"`
  157. AmountDue int `json:"amount_due"`
  158. AmountPaid int `json:"amount_paid"`
  159. Status string `json:"status"`
  160. Type string `json:"type"`
  161. Transaction string `json:"transaction"`
  162. CreatedAt string `json:"created_at"`
  163. UpdatedAt string `json:"updated_at"`
  164. Mode string `json:"mode"`
  165. } `json:"order"`
  166. Product struct {
  167. Id string `json:"id"`
  168. Object string `json:"object"`
  169. Name string `json:"name"`
  170. Description string `json:"description"`
  171. Price int `json:"price"`
  172. Currency string `json:"currency"`
  173. BillingType string `json:"billing_type"`
  174. BillingPeriod string `json:"billing_period"`
  175. Status string `json:"status"`
  176. TaxMode string `json:"tax_mode"`
  177. TaxCategory string `json:"tax_category"`
  178. DefaultSuccessUrl *string `json:"default_success_url"`
  179. CreatedAt string `json:"created_at"`
  180. UpdatedAt string `json:"updated_at"`
  181. Mode string `json:"mode"`
  182. } `json:"product"`
  183. Units int `json:"units"`
  184. Customer struct {
  185. Id string `json:"id"`
  186. Object string `json:"object"`
  187. Email string `json:"email"`
  188. Name string `json:"name"`
  189. Country string `json:"country"`
  190. CreatedAt string `json:"created_at"`
  191. UpdatedAt string `json:"updated_at"`
  192. Mode string `json:"mode"`
  193. } `json:"customer"`
  194. Status string `json:"status"`
  195. Metadata map[string]string `json:"metadata"`
  196. Mode string `json:"mode"`
  197. } `json:"object"`
  198. }
  199. // 保留旧的结构体作为兼容
  200. type CreemWebhookData struct {
  201. Type string `json:"type"`
  202. Data struct {
  203. RequestId string `json:"request_id"`
  204. Status string `json:"status"`
  205. Metadata map[string]string `json:"metadata"`
  206. } `json:"data"`
  207. }
  208. func CreemWebhook(c *gin.Context) {
  209. // 读取body内容用于打印,同时保留原始数据供后续使用
  210. bodyBytes, err := io.ReadAll(c.Request.Body)
  211. if err != nil {
  212. log.Printf("读取Creem Webhook请求body失败: %v", err)
  213. c.AbortWithStatus(http.StatusBadRequest)
  214. return
  215. }
  216. // 获取签名头
  217. signature := c.GetHeader(CreemSignatureHeader)
  218. // 打印请求信息用于调试
  219. log.Printf("Creem Webhook - URI: %s, Query: %s", c.Request.RequestURI, c.Request.URL.RawQuery)
  220. log.Printf("Creem Webhook - Signature: %s", signature)
  221. log.Printf("Creem Webhook - Body: %s", string(bodyBytes))
  222. // 验证签名
  223. if !verifyCreemSignature(string(bodyBytes), signature, setting.CreemWebhookSecret) {
  224. log.Printf("Creem Webhook签名验证失败")
  225. c.AbortWithStatus(http.StatusUnauthorized)
  226. return
  227. }
  228. log.Printf("Creem Webhook签名验证成功")
  229. // 重新设置body供后续的ShouldBindJSON使用
  230. c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes))
  231. // 解析新格式的webhook数据
  232. var webhookEvent CreemWebhookEvent
  233. if err := c.ShouldBindJSON(&webhookEvent); err != nil {
  234. log.Printf("解析Creem Webhook参数失败: %v", err)
  235. c.AbortWithStatus(http.StatusBadRequest)
  236. return
  237. }
  238. log.Printf("Creem Webhook解析成功 - EventType: %s, EventId: %s", webhookEvent.EventType, webhookEvent.Id)
  239. // 根据事件类型处理不同的webhook
  240. switch webhookEvent.EventType {
  241. case "checkout.completed":
  242. handleCheckoutCompleted(c, &webhookEvent)
  243. default:
  244. log.Printf("忽略Creem Webhook事件类型: %s", webhookEvent.EventType)
  245. c.Status(http.StatusOK)
  246. }
  247. }
  248. // 处理支付完成事件
  249. func handleCheckoutCompleted(c *gin.Context, event *CreemWebhookEvent) {
  250. // 验证订单状态
  251. if event.Object.Order.Status != "paid" {
  252. log.Printf("订单状态不是已支付: %s, 跳过处理", event.Object.Order.Status)
  253. c.Status(http.StatusOK)
  254. return
  255. }
  256. // 获取引用ID(这是我们创建订单时传递的request_id)
  257. referenceId := event.Object.RequestId
  258. if referenceId == "" {
  259. log.Println("Creem Webhook缺少request_id字段")
  260. c.AbortWithStatus(http.StatusBadRequest)
  261. return
  262. }
  263. // 验证订单类型,目前只处理一次性付款
  264. if event.Object.Order.Type != "onetime" {
  265. log.Printf("暂不支持的订单类型: %s, 跳过处理", event.Object.Order.Type)
  266. c.Status(http.StatusOK)
  267. return
  268. }
  269. // 记录详细的支付信息
  270. log.Printf("处理Creem支付完成 - 订单号: %s, Creem订单ID: %s, 支付金额: %d %s, 客户邮箱: %s, 产品: %s",
  271. referenceId,
  272. event.Object.Order.Id,
  273. event.Object.Order.AmountPaid,
  274. event.Object.Order.Currency,
  275. event.Object.Customer.Email,
  276. event.Object.Product.Name)
  277. // 查询本地订单确认存在
  278. topUp := model.GetTopUpByTradeNo(referenceId)
  279. if topUp == nil {
  280. log.Printf("Creem充值订单不存在: %s", referenceId)
  281. c.AbortWithStatus(http.StatusBadRequest)
  282. return
  283. }
  284. if topUp.Status != common.TopUpStatusPending {
  285. log.Printf("Creem充值订单状态错误: %s, 当前状态: %s", referenceId, topUp.Status)
  286. c.Status(http.StatusOK) // 已处理过的订单,返回成功避免重复处理
  287. return
  288. }
  289. // 处理充值,传入客户邮箱和姓名信息
  290. customerEmail := event.Object.Customer.Email
  291. customerName := event.Object.Customer.Name
  292. // 防护性检查,确保邮箱和姓名不为空字符串
  293. if customerEmail == "" {
  294. log.Printf("警告:Creem回调中客户邮箱为空 - 订单号: %s", referenceId)
  295. }
  296. if customerName == "" {
  297. log.Printf("警告:Creem回调中客户姓名为空 - 订单号: %s", referenceId)
  298. }
  299. err := model.RechargeCreem(referenceId, customerEmail, customerName)
  300. if err != nil {
  301. log.Printf("Creem充值处理失败: %s, 订单号: %s", err.Error(), referenceId)
  302. c.AbortWithStatus(http.StatusInternalServerError)
  303. return
  304. }
  305. log.Printf("Creem充值成功 - 订单号: %s, 充值额度: %d, 支付金额: %.2f, 客户邮箱: %s, 客户姓名: %s",
  306. referenceId, topUp.Amount, topUp.Money, customerEmail, customerName)
  307. c.Status(http.StatusOK)
  308. }
  309. type CreemCheckoutRequest struct {
  310. ProductId string `json:"product_id"`
  311. RequestId string `json:"request_id"`
  312. Customer struct {
  313. Email string `json:"email"`
  314. } `json:"customer"`
  315. Metadata map[string]string `json:"metadata,omitempty"`
  316. }
  317. type CreemCheckoutResponse struct {
  318. CheckoutUrl string `json:"checkout_url"`
  319. Id string `json:"id"`
  320. }
  321. func genCreemLink(referenceId string, product *CreemProduct, email string, username string) (string, error) {
  322. if setting.CreemApiKey == "" {
  323. return "", fmt.Errorf("未配置Creem API密钥")
  324. }
  325. // 根据测试模式选择 API 端点
  326. apiUrl := "https://api.creem.io/v1/checkouts"
  327. if setting.CreemTestMode {
  328. apiUrl = "https://test-api.creem.io/v1/checkouts"
  329. log.Printf("使用Creem测试环境: %s", apiUrl)
  330. }
  331. // 构建请求数据,确保包含用户邮箱
  332. requestData := CreemCheckoutRequest{
  333. ProductId: product.ProductId,
  334. RequestId: referenceId, // 这个作为订单ID传递给Creem
  335. Customer: struct {
  336. Email string `json:"email"`
  337. }{
  338. Email: email, // 用户邮箱会在支付页面预填充
  339. },
  340. Metadata: map[string]string{
  341. "username": username,
  342. "reference_id": referenceId,
  343. "product_name": product.Name,
  344. "quota": fmt.Sprintf("%d", product.Quota),
  345. },
  346. }
  347. // 序列化请求数据
  348. jsonData, err := json.Marshal(requestData)
  349. if err != nil {
  350. return "", fmt.Errorf("序列化请求数据失败: %v", err)
  351. }
  352. // 创建 HTTP 请求
  353. req, err := http.NewRequest("POST", apiUrl, bytes.NewBuffer(jsonData))
  354. if err != nil {
  355. return "", fmt.Errorf("创建HTTP请求失败: %v", err)
  356. }
  357. // 设置请求头
  358. req.Header.Set("Content-Type", "application/json")
  359. req.Header.Set("x-api-key", setting.CreemApiKey)
  360. log.Printf("发送Creem支付请求 - URL: %s, 产品ID: %s, 用户邮箱: %s, 订单号: %s",
  361. apiUrl, product.ProductId, email, referenceId)
  362. // 发送请求
  363. client := &http.Client{
  364. Timeout: 30 * time.Second,
  365. }
  366. resp, err := client.Do(req)
  367. if err != nil {
  368. return "", fmt.Errorf("发送HTTP请求失败: %v", err)
  369. }
  370. defer resp.Body.Close()
  371. // 读取响应
  372. body, err := io.ReadAll(resp.Body)
  373. if err != nil {
  374. return "", fmt.Errorf("读取响应失败: %v", err)
  375. }
  376. log.Printf("Creem API响应 - 状态码: %d, 响应体: %s", resp.StatusCode, string(body))
  377. // 检查响应状态
  378. if resp.StatusCode != http.StatusOK {
  379. return "", fmt.Errorf("Creem API 返回错误状态 %d: %s", resp.StatusCode, string(body))
  380. }
  381. // 解析响应
  382. var checkoutResp CreemCheckoutResponse
  383. err = json.Unmarshal(body, &checkoutResp)
  384. if err != nil {
  385. return "", fmt.Errorf("解析响应失败: %v", err)
  386. }
  387. if checkoutResp.CheckoutUrl == "" {
  388. return "", fmt.Errorf("Creem API 未返回支付链接")
  389. }
  390. log.Printf("Creem 支付链接创建成功 - 订单号: %s, 支付链接: %s", referenceId, checkoutResp.CheckoutUrl)
  391. return checkoutResp.CheckoutUrl, nil
  392. }