wechat.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. type wechatResp struct {
  17. Status int `json:"status"`
  18. Msg string `json:"msg"`
  19. }
  20. const (
  21. // http://info.bilibili.co/pages/viewpage.action?pageId=5406728
  22. _url = "http://bap.bilibili.co/api/v1/message/add"
  23. )
  24. // SendWechat 发送企业微信消息
  25. func (d *Dao) SendWechat(msg string) (err error) {
  26. log.Error("SendWechat logged error(%s)", msg)
  27. params := map[string]string{
  28. "content": msg,
  29. "timestamp": strconv.FormatInt(time.Now().Unix(), 10),
  30. "token": d.c.Wechat.Token,
  31. "type": "wechat",
  32. "username": d.c.Wechat.Username,
  33. "url": "",
  34. }
  35. params["signature"] = d.sign(params)
  36. b, err := json.Marshal(params)
  37. if err != nil {
  38. log.Error("SendWechat json.Marshal error(%v)", err)
  39. return
  40. }
  41. req, err := http.NewRequest(http.MethodPost, _url, bytes.NewReader(b))
  42. if err != nil {
  43. log.Error("SendWechat NewRequest error(%v), params(%s)", err, string(b))
  44. return
  45. }
  46. req.Header.Set("Content-Type", "application/json; charset=utf-8")
  47. res := wechatResp{}
  48. if err = d.httpClient.Do(context.TODO(), req, &res); err != nil {
  49. log.Error("SendWechat Do error(%v), params(%s)", err, string(b))
  50. return
  51. }
  52. if res.Status != 0 {
  53. err = fmt.Errorf("status(%d) msg(%s)", res.Status, res.Msg)
  54. log.Error("SendWechat response error(%v), params(%s)", err, string(b))
  55. }
  56. return
  57. }
  58. func (d *Dao) sign(params map[string]string) string {
  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. h := md5.New()
  73. io.WriteString(h, buf.String()+d.c.Wechat.Secret)
  74. return fmt.Sprintf("%x", h.Sum(nil))
  75. }