topup_creem.go 17 KB

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