wechat.go 1.9 KB

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