merak.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package cms
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/sha1"
  6. "encoding/hex"
  7. "encoding/json"
  8. "net/http"
  9. "sort"
  10. "strings"
  11. "go-common/library/log"
  12. "github.com/pkg/errors"
  13. )
  14. // MerakNotify send notify
  15. func (d *Dao) MerakNotify(ctx context.Context, title, content string) (err error) {
  16. var (
  17. cfg = d.conf.Cfg.Merak
  18. sign string
  19. req *http.Request
  20. body []byte
  21. )
  22. params := map[string]string{
  23. "Action": "CreateWechatMessage",
  24. "PublicKey": cfg.Key,
  25. "UserName": strings.Join(cfg.Names, ","),
  26. "Title": title,
  27. "Content": content,
  28. "TreeId": "",
  29. }
  30. if sign, err = MerakSign(params, cfg.Secret); err != nil {
  31. log.Error("MerakNotify Failed to sign params: %+v: %+v", params, err)
  32. return err
  33. }
  34. params["Signature"] = sign
  35. if body, err = json.Marshal(params); err != nil {
  36. log.Error("MerakNotify Json %v, Err %v", params, err)
  37. return
  38. }
  39. if req, err = http.NewRequest(http.MethodPost, cfg.Host, bytes.NewReader(body)); err != nil {
  40. log.Error("MerakNotify NewRequest Err %v, Host %v", err, cfg.Host)
  41. return
  42. }
  43. req.Header.Set("Content-Type", "application/json; charset=utf-8")
  44. res := struct {
  45. Action string `json:"Action"`
  46. RetCode int `json:"RetCode"`
  47. Data []string `json:"Data"`
  48. }{}
  49. if err = d.client.Do(ctx, req, &res); err != nil {
  50. return
  51. }
  52. if res.RetCode != 0 {
  53. err = errors.Errorf("Merak error: %d", res.RetCode)
  54. log.Error("Failed to send notify by merak with params: %+v: %+v", string(body), err)
  55. return
  56. }
  57. return
  58. }
  59. // MerakSign is used to sign for merak wechat msg
  60. func MerakSign(params map[string]string, secret string) (string, error) {
  61. keys := make([]string, 0, len(params))
  62. for k := range params {
  63. keys = append(keys, k)
  64. }
  65. sort.Strings(keys)
  66. buf := bytes.Buffer{}
  67. for _, k := range keys {
  68. buf.WriteString(k + params[k])
  69. }
  70. h := sha1.New()
  71. if _, err := h.Write(buf.Bytes()); err != nil {
  72. return "", errors.WithStack(err)
  73. }
  74. if _, err := h.Write([]byte(secret)); err != nil {
  75. return "", errors.WithStack(err)
  76. }
  77. sum := h.Sum(nil)
  78. return hex.EncodeToString(sum), nil
  79. }