webhook_middleware.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package middleware
  2. import (
  3. "encoding/json"
  4. "eta/eta_mini_ht_api/common/component/config"
  5. logger "eta/eta_mini_ht_api/common/component/log"
  6. "eta/eta_mini_ht_api/common/contants"
  7. "eta/eta_mini_ht_api/common/utils/auth"
  8. "fmt"
  9. "github.com/beego/beego/v2/server/web"
  10. "github.com/beego/beego/v2/server/web/context"
  11. "strings"
  12. )
  13. var (
  14. htConfig = config.GetConfig(contants.HT).(*config.HTBizConfig)
  15. )
  16. func WebHookAuthMiddleware() web.FilterFunc {
  17. return func(ctx *context.Context) {
  18. if strings.Contains(ctx.Input.URL(), "payment") || strings.Contains(ctx.Input.URL(), "es/delete") {
  19. return
  20. }
  21. body := ctx.Input.RequestBody
  22. webhookRequest := new(WebhookRequest)
  23. err := json.Unmarshal(body, &webhookRequest)
  24. if err != nil {
  25. rep := webhookUnauthorized("请求参数异常")
  26. logger.Error("WebhookRequest解析失败: %v", err)
  27. _ = ctx.JSONResp(rep)
  28. return
  29. }
  30. privateKey, err := auth.ParsePrivateKey(htConfig.GetWebhookPrivateKey())
  31. if err != nil {
  32. rep := webhookSysErr("系统异常")
  33. logger.Error("解析私钥失败: %v", err)
  34. _ = ctx.JSONResp(rep)
  35. return
  36. }
  37. logger.Info("解码请求: %v", webhookRequest.Data)
  38. decodeData, err := auth.DecryptWithRSA(privateKey, webhookRequest.Data)
  39. if err != nil {
  40. rep := webhookSysErr("解密请求体失败")
  41. logger.Error("解密请求体失败: %v", err)
  42. _ = ctx.JSONResp(rep)
  43. return
  44. }
  45. fmt.Printf("解密后的请求: %v", string(decodeData))
  46. ctx.Input.RequestBody = decodeData
  47. return
  48. }
  49. }
  50. type WebhookRequest struct {
  51. Data string `json:"data"`
  52. }