wechat.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package bnj
  2. import (
  3. "context"
  4. "encoding/json"
  5. "net/http"
  6. "strings"
  7. "go-common/library/ecode"
  8. "go-common/library/log"
  9. )
  10. const (
  11. _wechatAction = "NotifyCreate"
  12. _wechatType = "wechat_message"
  13. _wechatURL = "http://merak.bilibili.co"
  14. )
  15. // SendWechat send wechat work message.
  16. func (d *Dao) SendWechat(c context.Context, title, msg, user string) (err error) {
  17. var msgBytes []byte
  18. params := map[string]interface{}{
  19. "Action": _wechatAction,
  20. "SendType": _wechatType,
  21. "PublicKey": d.c.Bnj2019.WxKey,
  22. "UserName": user,
  23. "Content": map[string]string{
  24. "subject": title,
  25. "body": title + "\n" + msg,
  26. },
  27. "TreeId": "",
  28. "Signature": "1",
  29. "Severity": "P5",
  30. }
  31. if msgBytes, err = json.Marshal(params); err != nil {
  32. return
  33. }
  34. var req *http.Request
  35. if req, err = http.NewRequest(http.MethodPost, _wechatURL, strings.NewReader(string(msgBytes))); err != nil {
  36. return
  37. }
  38. req.Header.Add("content-type", "application/json; charset=UTF-8")
  39. res := &struct {
  40. RetCode int `json:"RetCode"`
  41. }{}
  42. if err = d.client.Do(c, req, &res); err != nil {
  43. log.Error("SendWechat d.client.Do(title:%s,msg:%s,user:%s) error(%v)", title, msg, user, err)
  44. return
  45. }
  46. if res.RetCode != 0 {
  47. err = ecode.Int(res.RetCode)
  48. log.Error("SendWechat d.client.Do(title:%s,msg:%s,user:%s) error(%v)", title, msg, user, err)
  49. return
  50. }
  51. return
  52. }