message.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package dao
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/md5"
  6. "encoding/json"
  7. "fmt"
  8. "io"
  9. "net/http"
  10. "net/url"
  11. "sort"
  12. "strconv"
  13. "time"
  14. "go-common/library/log"
  15. )
  16. // wechatResp 企业微信的响应
  17. type wechatResp struct {
  18. Msg string `json:"msg"`
  19. Status int `json:"status"`
  20. }
  21. // WechatMessage 发送企业微信消息
  22. func (d *Dao) WechatMessage(content string) (err error) {
  23. params := map[string]string{
  24. "content": content,
  25. "timestamp": strconv.FormatInt(time.Now().Unix(), 10),
  26. "title": "",
  27. "token": d.c.Wechat.Token,
  28. "type": "wechat",
  29. "username": d.c.Wechat.UserName,
  30. "url": "",
  31. }
  32. params["signature"] = d.signature(params, d.c.Wechat.Secret)
  33. b, err := json.Marshal(params)
  34. if err != nil {
  35. log.Error("WechatMessage json.Marshal error(%v)", err)
  36. return
  37. }
  38. req, err := http.NewRequest(http.MethodPost, "http://bap.bilibili.co/api/v1/message/add", bytes.NewReader(b))
  39. if err != nil {
  40. log.Error("WechatMessage NewRequest error(%v), params(%s)", err, string(b))
  41. return
  42. }
  43. req.Header.Set("Content-Type", "application/json; charset=utf-8")
  44. res := wechatResp{}
  45. if err = d.httpClient.Do(context.TODO(), req, &res); err != nil {
  46. log.Error("WechatMessage Do error(%v), params(%s)", err, string(b))
  47. return
  48. }
  49. if res.Status != 0 {
  50. err = fmt.Errorf("status(%d) msg(%s)", res.Status, res.Msg)
  51. log.Error("WechatMessage response error(%v), params(%s)", err, string(b))
  52. return
  53. }
  54. return
  55. }
  56. // signature 加密算法
  57. func (d *Dao) signature(params map[string]string, secret string) string {
  58. // content=xxx&timestamp=xxx格式
  59. keys := []string{}
  60. for k := range params {
  61. keys = append(keys, k)
  62. }
  63. sort.Strings(keys)
  64. buf := bytes.Buffer{}
  65. for _, k := range keys {
  66. if buf.Len() > 0 {
  67. buf.WriteByte('&')
  68. }
  69. buf.WriteString(url.QueryEscape(k) + "=")
  70. buf.WriteString(url.QueryEscape(params[k]))
  71. }
  72. // 加密
  73. h := md5.New()
  74. io.WriteString(h, buf.String()+secret)
  75. return fmt.Sprintf("%x", h.Sum(nil))
  76. }