workChatSendMsg.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package public
  2. import (
  3. "app.yhyue.com/moapp/jybase/common"
  4. "app.yhyue.com/moapp/jybase/redis"
  5. "biBackService/config"
  6. "bytes"
  7. "encoding/json"
  8. "fmt"
  9. "io/ioutil"
  10. "log"
  11. "net/http"
  12. )
  13. const (
  14. TOKEN = "qywx_token"
  15. )
  16. type tokeObj struct {
  17. Errcode int `json:"errcode"`
  18. Errmsg string `json:"errmsg"`
  19. Access_token string `json:"access_token"`
  20. Expires_in int `json:"expires_in"`
  21. }
  22. /*func SendInfo(key, msg string) {
  23. if t, err := redis.Exists("workChat", key); !t && err == nil {
  24. redis.Put("workChat", key, 1, 86400)
  25. SendMsg("rr", "", msg)
  26. }
  27. }*/
  28. func SendMsg(userid string, msg ...string) (bool, error) {
  29. con := ""
  30. if len(msg) == 1 {
  31. con = msg[0]
  32. }
  33. m := map[string]interface{}{
  34. "touser": userid,
  35. "msgtype": "text",
  36. "agentid": config.SysConfig.WorkPrivateMsg.AgentID,
  37. "text": map[string]string{
  38. "content": con,
  39. },
  40. }
  41. b, _ := json.Marshal(m)
  42. reqUrl := fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s", getToken())
  43. //log.Println("发送url:", reqUrl)
  44. res, err := http.Post(reqUrl, "application/json", bytes.NewReader(b))
  45. if err != nil {
  46. log.Print(err)
  47. } else {
  48. defer res.Body.Close()
  49. bs, _ := ioutil.ReadAll(res.Body)
  50. //log.Info(string(bs))
  51. var respData map[string]interface{}
  52. json.Unmarshal(bs, &respData)
  53. log.Println("respData", respData)
  54. if respData != nil && fmt.Sprintf("%v", respData["errcode"]) == "0" {
  55. return true, nil
  56. }
  57. }
  58. return false, err
  59. }
  60. func getToken() string {
  61. token := common.InterfaceToStr(redis.Get("workChat", TOKEN))
  62. if token == "" {
  63. tokenUrl := fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s", config.SysConfig.WorkPrivateMsg.WxCorpid, config.SysConfig.WorkPrivateMsg.WxSecret)
  64. //log.Println("tokenUrl", tokenUrl)
  65. res, err := http.Get(tokenUrl)
  66. if err != nil {
  67. log.Print(err)
  68. } else {
  69. defer res.Body.Close()
  70. bs, err1 := ioutil.ReadAll(res.Body)
  71. if err1 != nil {
  72. log.Print(err1)
  73. } else {
  74. var tokes tokeObj
  75. err2 := json.Unmarshal(bs, &tokes)
  76. if err2 != nil {
  77. log.Print(err2)
  78. } else {
  79. token = tokes.Access_token
  80. if tokes.Expires_in > 1800 {
  81. redis.Put("workChat", TOKEN, token, 1800)
  82. }
  83. }
  84. }
  85. }
  86. }
  87. return token
  88. }