wechat.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. _url = "http://bap.bilibili.co/api/v1/message/add"
  22. )
  23. // SendWechat 发送企业微信消息
  24. func (d *Dao) SendWechat(content string) (err error) {
  25. params := map[string]string{
  26. "content": content,
  27. "timestamp": strconv.FormatInt(time.Now().Unix(), 10),
  28. "token": d.c.Wechat.Token,
  29. "type": "wechat",
  30. "username": d.c.Wechat.Username,
  31. "url": "",
  32. }
  33. params["signature"] = d.sign(params)
  34. b, err := json.Marshal(params)
  35. if err != nil {
  36. log.Error("SendWechat json.Marshal error(%v)", err)
  37. return
  38. }
  39. req, err := http.NewRequest(http.MethodPost, _url, bytes.NewReader(b))
  40. if err != nil {
  41. log.Error("SendWechat NewRequest error(%v), params(%s)", err, string(b))
  42. return
  43. }
  44. req.Header.Set("Content-Type", "application/json; charset=utf-8")
  45. res := wechatResp{}
  46. if err = d.httpClient.Do(context.TODO(), req, &res); err != nil {
  47. log.Error("SendWechat Do error(%v), params(%s)", err, string(b))
  48. return
  49. }
  50. if res.Status != 0 {
  51. err = fmt.Errorf("status(%d) msg(%s)", res.Status, res.Msg)
  52. log.Error("SendWechat response error(%v), params(%s)", err, string(b))
  53. }
  54. return
  55. }
  56. func (d *Dao) sign(params map[string]string) string {
  57. keys := []string{}
  58. for k := range params {
  59. keys = append(keys, k)
  60. }
  61. sort.Strings(keys)
  62. buf := bytes.Buffer{}
  63. for _, k := range keys {
  64. if buf.Len() > 0 {
  65. buf.WriteByte('&')
  66. }
  67. buf.WriteString(url.QueryEscape(k) + "=")
  68. buf.WriteString(url.QueryEscape(params[k]))
  69. }
  70. h := md5.New()
  71. io.WriteString(h, buf.String()+d.c.Wechat.Secret)
  72. return fmt.Sprintf("%x", h.Sum(nil))
  73. }