topup_creem.go 14 KB

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